Jump to content

Connect Leeroopedia MCP: Equip your AI agents to search best practices, build plans, verify code, diagnose failures, and look up hyperparameter defaults.

Implementation:Diagram of thought Diagram of thought Graphviz DAG Visualization

From Leeroopedia

Template:Implementation

Overview

Graphviz DAG Visualization is the concrete tool for rendering DoT reasoning DAGs as visual graphs using the Graphviz DOT format. Nodes are color-coded by role and validation status, edges are labeled by kind, and the resulting output serves as the primary visual artifact of the Trace Report Generation principle.

Description

This implementation uses Graphviz to create visual representations of reasoning DAGs produced by the Diagram of Thought framework. The key visual conventions are:

  • Nodes are color-coded by their role: problem (light blue), proposer (light green), critic (light yellow), summarizer (light coral).
  • Node borders indicate validation status: green for validated, red for invalidated, black for pending/unreviewed.
  • Edges are labeled with their kind (use, critique, refine) to make dependency relationships explicit.

The DOT format output can be rendered to SVG, PNG, or PDF via the Graphviz toolchain, or consumed programmatically by any DOT-compatible library.

Usage

Invoke after DAG analysis is complete, when creating visual reports for auditing, debugging, or archival. The typical workflow is:

  1. Extract the DAG from the reasoning trace (parse @node, @edge, @status records).
  2. Run analysis to compute statistics and validation summaries.
  3. Call the report generator to produce DOT source and statistics text.
  4. Render the DOT source to the desired output format.

Code Reference

Source

  • README.md:L22 — "auditable and verifiable traces" via the typed serialization protocol.
  • README.md:L116-130 — Structural and semantic views of the reasoning process.

Signature

def generate_dot_report(
    adjacency: dict[str, list[dict]],
    metadata: dict[str, dict],
    analysis: dict
) -> str:
    """Generate a Graphviz DOT format string from the DoT reasoning DAG.

    Parameters
    ----------
    adjacency : dict[str, list[dict]]
        Adjacency list mapping source node IDs to lists of edge dicts,
        each containing 'dst' and 'kind' keys.
    metadata : dict[str, dict]
        Per-node metadata with 'role' and optional 'status' keys.
    analysis : dict
        Analysis results (used for optional annotation).

    Returns
    -------
    str
        Complete DOT format source string ready for Graphviz rendering.
    """

Import

Graphviz can be used either through the Python binding or by generating DOT format strings directly:

# Option A: Using the graphviz Python package
import graphviz

# Option B: Generating DOT strings directly (no external dependency)
# No import needed; produce DOT source as plain text and invoke
# the `dot` CLI tool or pass to a downstream renderer.

I/O Contract

Direction Name Type Description
Input adjacency dict[str, list[dict]] DAG adjacency list. Each key is a source node ID; each value is a list of edge dicts with keys dst (destination node ID) and kind (use, critique, or refine).
Input metadata dict[str, dict] Per-node metadata. Each entry has keys role (problem, proposer, critic, summarizer) and optionally status (validated, invalidated).
Input analysis dict Analysis results including keys such as total_nodes, validated_nodes, invalidated_nodes, validation_ratio, critical_path, and branch_points.
Output DOT source str Complete Graphviz DOT format string representing the reasoning DAG.
Output Visual graph SVG / PNG / PDF Rendered graph image produced by the Graphviz engine from the DOT source.
Output Statistics text str Human-readable summary of trace statistics and validation metrics.

Usage Examples

Generating DOT Format

def generate_dot_report(adjacency, metadata, analysis):
    dot_lines = ["digraph DoT {", '  rankdir=TB;', '  node [shape=box];']

    # Color nodes by role and status
    role_colors = {
        "problem": "lightblue",
        "proposer": "lightgreen",
        "critic": "lightyellow",
        "summarizer": "lightcoral",
    }
    for nid, m in metadata.items():
        color = role_colors.get(m["role"], "white")
        border = (
            "red" if m.get("status") == "invalidated"
            else "green" if m.get("status") == "validated"
            else "black"
        )
        dot_lines.append(
            f'  {nid} [label="Node {nid}\\n{m["role"]}" '
            f'fillcolor="{color}" style=filled color="{border}"];'
        )

    for src, neighbors in adjacency.items():
        for edge in neighbors:
            dot_lines.append(
                f'  {src} -> {edge["dst"]} [label="{edge["kind"]}"];'
            )

    dot_lines.append("}")
    return "\n".join(dot_lines)

Example invocation:

adjacency = {
    "1": [{"dst": "2", "kind": "use"}],
    "2": [{"dst": "3", "kind": "critique"}, {"dst": "4", "kind": "refine"}],
    "2": [{"dst": "3", "kind": "critique"}, {"dst": "4", "kind": "refine"}, {"dst": "5", "kind": "use"}],
}
metadata = {
    "1": {"role": "problem"},
    "2": {"role": "proposer", "status": "validated"},
    "3": {"role": "critic"},
    "4": {"role": "proposer", "status": "invalidated"},
    "5": {"role": "summarizer"},
}

dot_source = generate_dot_report(adjacency, metadata, {})
print(dot_source)

Generating Statistics

def generate_statistics(analysis):
    return f"""DoT Trace Report
================
Total nodes: {analysis['total_nodes']}
Validated: {len(analysis['validated_nodes'])}
Invalidated: {len(analysis['invalidated_nodes'])}
Validation ratio: {analysis['validation_ratio']:.1%}
Critical path length: {len(analysis['critical_path'])}
Branch points: {len(analysis['branch_points'])}"""

Example invocation:

analysis = {
    "total_nodes": 5,
    "validated_nodes": ["2"],
    "invalidated_nodes": ["4"],
    "validation_ratio": 0.5,
    "critical_path": ["1", "2", "5"],
    "branch_points": ["2"],
}

print(generate_statistics(analysis))
# DoT Trace Report
# ================
# Total nodes: 5
# Validated: 1
# Invalidated: 1
# Validation ratio: 50.0%
# Critical path length: 3
# Branch points: 1

Rendering to File

# Using the graphviz Python package
import graphviz

dot_source = generate_dot_report(adjacency, metadata, analysis)
graph = graphviz.Source(dot_source)
graph.render("dot_trace_report", format="svg", cleanup=True)

# Or using the CLI directly
import subprocess

with open("trace.dot", "w") as f:
    f.write(dot_source)

subprocess.run(["dot", "-Tsvg", "trace.dot", "-o", "trace.svg"], check=True)

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment