Mermaid.js + AI: Generating Diagrams from Natural Language
How we turn a single sentence into a system diagram using Mermaid.js and an LLM — the prompt design, validation loop, and rendering pipeline behind DiagramAI Studio.
Diagrams are how engineers think, but drawing them is tedious. Mermaid.js renders diagrams from plain text, which makes it the perfect output target for an LLM. Combine the two and you can turn “a user signs up, we email them, then create a Stripe customer” into a flowchart in seconds. Here is how we built it.
Why Mermaid is the ideal target
LLMs are excellent at producing structured text and far less reliable at pixel-perfect layout. Mermaid lets the model do what it is good at — emit a concise, declarative description — while a deterministic renderer handles layout. The model writes syntax; Mermaid draws.
Designing the prompt
The trick is constraining the model to valid Mermaid and a single diagram type per request. We give it the grammar, one worked example, and a hard instruction to return only a fenced code block.
SYSTEM = """You convert descriptions into valid Mermaid 'flowchart TD'.
Rules:
- Output ONLY a mermaid code block, nothing else.
- Use short node ids (A, B, C) with descriptive labels.
- Never invent steps the user did not mention.
"""The validation loop
Models occasionally emit invalid syntax. Rather than show the user an error, we parse the output with Mermaid’s own parser; if it throws, we send the error back to the model and ask it to fix the diagram. One retry resolves the vast majority of failures.
import mermaid from "mermaid";
async function safeRender(code: string) {
try {
await mermaid.parse(code); // throws on invalid syntax
return await mermaid.render("id", code);
} catch (err) {
return repairWithLLM(code, String(err)); // one-shot self-heal
}
}Rendering safely on the client
Mermaid renders to SVG in the browser. Sanitize the output and render in a sandboxed container so untrusted input can never inject scripts — standard hygiene whenever you turn model output into markup.
Run it fully local
Because the model only needs to emit short structured text, a small local model handles it well — no API bill for what can become a very chatty feature. We discuss that trade-off in depth in our local AI vs. API guide.
Key takeaways
- Let the LLM emit text; let Mermaid handle layout.
- Constrain output to one diagram type and a code block.
- Add a parse-and-repair loop for reliability.
- Sanitize before rendering model-generated markup.
Want an AI feature like this inside your product? It is exactly the kind of thing our AI engineering team ships. Start a conversation.