# How Litho Generates Mermaid Syntax for Diagrams: Inside the deepwiki-rs Pipeline

> Discover how Litho generates Mermaid syntax for diagrams via LLM prompting, programmatic construction, and automated post-processing within the deepwiki-rs pipeline. Learn the inner workings.

- Repository: [Sopaco/deepwiki-rs](https://github.com/sopaco/deepwiki-rs)
- Tags: internals
- Published: 2026-02-16

---

**Litho generates Mermaid syntax through a three-stage pipeline involving LLM prompting for architecture diagrams, programmatic construction for database ER diagrams, and automated post-processing to fix syntax errors.**

Litho is the documentation engine powering the `sopaco/deepwiki-rs` repository, designed to automatically analyze codebases and produce comprehensive technical documentation. A core capability of this system is the generation of Mermaid diagrams for visualizing system architecture and database relationships without manual intervention.

## LLM-Driven Mermaid Generation via the Architecture Researcher

The primary mechanism for generating high-level architecture diagrams relies on prompting Large Language Models (LLMs) to emit properly formatted Mermaid code.

### Prompt Engineering for Mermaid Output

In [`/src/generator/research/agents/architecture_researcher.rs`](https://github.com/sopaco/deepwiki-rs/blob/main//src/generator/research/agents/architecture_researcher.rs), the system constructs a `PromptTemplate` that explicitly instructs the LLM to return Mermaid syntax. Lines 57-63 contain the critical closing instruction:

```rust
closing_instruction: r#"

## Analysis Requirements:

- Draw system architecture diagram…
- Use mermaid format to represent architecture relationships
…"#.to_string(),

```

When the LLM processes this prompt, it returns a fenced code block containing valid Mermaid syntax. The system then extracts this block from the response and stores it in the research report structure defined in [`/src/generator/research/types.rs`](https://github.com/sopaco/deepwiki-rs/blob/main//src/generator/research/types.rs), specifically within fields like `flowchart_mermaid` and `sequence_diagram_mermaid`.

## Programmatic Mermaid Construction for Database ER Diagrams

While architecture diagrams rely on LLM generation, database entity-relationship diagrams are constructed programmatically to ensure precision in relationship cardinality and constraint naming.

### The Database Editor Agent

The [`/src/generator/compose/agents/database_editor.rs`](https://github.com/sopaco/deepwiki-rs/blob/main//src/generator/compose/agents/database_editor.rs) file contains the logic for manually assembling Mermaid `erDiagram` blocks. At line 147, the agent initializes the diagram structure:

```rust
content.push_str("```mermaid\nerDiagram\n");

```

### Formatting Relationship Lines

The helper function `format_relationship_mermaid` (lines 73-81) constructs individual relationship lines using Mermaid's ER diagram syntax. It maps internal relationship types to the correct Mermaid connectors:

```rust
fn format_relationship_mermaid(&self, content: &mut String, rel: &TableRelationship) {
    let from_table = rel.from_table.split('.').last().unwrap_or(&rel.from_table);
    let to_table   = rel.to_table.split('.').last().unwrap_or(&rel.to_table);

    let rel_symbol = match rel.relationship_type.as_str() {
        "ForeignKey" => "}o--||",
        "Reference" => "..>",
        _ => "--",
    };

    content.push_str(&format!(
        "    {} {} {} : \"{}\"\n",
        from_table, rel_symbol, to_table,
        rel.constraint_name.as_deref().unwrap_or("references")
    ));
}

```

This approach ensures that database diagrams accurately reflect foreign key constraints and table relationships without relying on the LLM to guess cardinality notation.

## Post-Processing and Syntax Validation

After generation, Litho optionally validates and repairs Mermaid syntax to handle occasional LLM hallucinations or formatting errors.

### The Mermaid-Fixer Component

Located in `/src/generator/outlet/fixer.rs` (lines 9-50), this component executes the external `mermaid-fixer` tool as a post-processing step. The implementation uses Tokio's process spawning:

```rust
if let Ok(output) = TokioCommand::new("mermaid-fixer")
        .arg("--directory")
        .arg(output_dir)
        .arg("--llm-model")
        .arg(llm_model)
        .arg("--verbose")
        .output()
        .await
{
    if !output.status.success() {
        eprintln!(
            "{}",
            context
                .config
                .target_language
                .msg_mermaid_error()
                .replace("{}", &String::from_utf8_lossy(&output.stderr))
        );
    }
}

```

This step is optional; if the `mermaid-fixer` binary is not found in the system PATH, Litho logs a warning at lines 42-44 and continues without syntax correction, ensuring the documentation generation pipeline remains resilient.

## Summary

- **LLM Prompting**: The Architecture Researcher agent explicitly requests Mermaid syntax in its prompt template, causing the LLM to return fenced code blocks ready for embedding.
- **Programmatic Generation**: The Database Editor constructs ER diagrams manually using `format_relationship_mermaid`, ensuring accurate cardinality symbols like `}o--||` for foreign keys.
- **Post-Processing**: The Mermaid-Fixer component optionally runs the external `mermaid-fixer` tool to repair syntax errors without blocking the generation pipeline.
- **Source Locations**: Key logic resides in [`architecture_researcher.rs`](https://github.com/sopaco/deepwiki-rs/blob/main/architecture_researcher.rs) (prompting), [`database_editor.rs`](https://github.com/sopaco/deepwiki-rs/blob/main/database_editor.rs) (ER construction), and [`fixer.rs`](https://github.com/sopaco/deepwiki-rs/blob/main/fixer.rs) (validation).

## Frequently Asked Questions

### How does Litho ensure Mermaid syntax is valid?

Litho employs a two-layer approach: first, it uses carefully engineered prompts to encourage the LLM to produce valid Mermaid code, and second, it runs the optional `mermaid-fixer` external tool via [`/src/generator/outlet/fixer.rs`](https://github.com/sopaco/deepwiki-rs/blob/main//src/generator/outlet/fixer.rs) to automatically detect and repair syntax errors in the generated output files.

### What types of diagrams can Litho generate?

According to the source code in `deepwiki-rs`, Litho can generate multiple diagram types including system architecture diagrams (via the Architecture Researcher), sequence diagrams (stored in `sequence_diagram_mermaid` fields), and database ER diagrams (via the Database Editor agent using `erDiagram` syntax).

### Where does Litho store generated Mermaid diagrams?

The generated Mermaid strings are stored in the research report structures defined in [`/src/generator/research/types.rs`](https://github.com/sopaco/deepwiki-rs/blob/main//src/generator/research/types.rs), specifically within fields like `flowchart_mermaid` and `sequence_diagram_mermaid`. These are later embedded into the final documentation output during the composition phase.

### Can Litho work without the mermaid-fixer tool?

Yes, the mermaid-fixer tool is optional. As implemented in [`/src/generator/outlet/fixer.rs`](https://github.com/sopaco/deepwiki-rs/blob/main//src/generator/outlet/fixer.rs) lines 42-44, if the tool is not found in the system PATH, Litho logs a warning message and continues the documentation generation process without performing the syntax correction step.