PHP Mermaid

Improving Code Quality with Consistent Mermaid Diagram Generation

Introduction

Ensuring consistent code quality and documentation can be a challenge. One area where consistency is crucial is in the generation of diagrams for technical documentation. This post discusses how we've improved the consistency and validity of Mermaid diagrams generated as part of our technical writing process for the devlog-ist/landing project, which provides a landing page for developer logs.

The Problem

Previously, the AI used to generate Mermaid diagrams sometimes produced invalid syntax. This resulted in diagrams that wouldn't render correctly, requiring manual correction and introducing inconsistencies. A common issue was the incorrect handling of special characters, particularly parentheses, within node labels. For example, labels like Rule::in() would cause errors unless properly escaped or quoted.

The Solution: Enhanced Prompt for Mermaid Syntax

To address this, we've enhanced the prompt used to guide the AI's diagram generation. Specifically, we've added explicit rules instructing the AI to:

  1. Always wrap node labels containing special characters in double quotes.
  2. Prefer bracket nodes A["Label"] over parenthesis nodes A("Label") to avoid potential parsing issues.
  3. Use simple alphanumeric labels when possible.

This ensures that the generated Mermaid syntax is valid and consistent, reducing the need for manual intervention.

Here's an example of how the prompt was updated to enforce these rules:

Before:

Generate a Mermaid diagram...

After:

Generate a Mermaid diagram. Node labels with special characters MUST be wrapped in double quotes: A["Rule::in()"] Characters (){}[] inside labels break the parser unless the label is quoted. Use simple alphanumeric labels when possible: A["Form Request"] not A(Form Request) Prefer bracket nodes A["Label"] over parenthesis nodes A("Label")

Example Diagram

Here's a simple example of a Mermaid diagram that adheres to the new syntax rules:

graph LR
    A["Form Request"] -- Validates --> B["Rule::in()"]
    B -- Passes --> C["Controller Action"]
    C -- Executes --> D["Database Update"]

Results

By implementing these changes, we've observed a significant reduction in the number of invalid Mermaid diagrams generated. This has streamlined our documentation process, improved consistency, and freed up time for more critical tasks.

Key Takeaway

Clear and precise instructions are essential for AI-powered content generation. By explicitly defining the required syntax rules, we can ensure that the generated output meets our quality standards and reduces the need for manual correction.

Improving Code Quality with Consistent Mermaid Diagram Generation
Gerardo Ruiz

Gerardo Ruiz

Author

Share: