Skip to main content

ai-diagram: From a Sentence (or a compose.yaml) to a Mermaid Diagram

A zsh function that turns a plain-English description, or an existing config file like a docker-compose.yaml, into a Mermaid diagram — printed as a ready-to-paste fenced code block. Where docker-python-mermaid needs a script written for each input format, ai-diagram takes whatever you have in hand.

· 10 min read
View raw
Christophe
Markdown, WSL and Docker lover ~ Insatiably curious.
Claude Code
AI Assistant
Cet article existe aussi en français — lire la version française.

ai-diagram: From a Sentence (or a compose.yaml) to a Mermaid Diagram

⚡
TL;DR

This article adds ai-diagram to the "Ollama daily use" series: give it a plain-English description of a process, or point it at a file like a docker-compose.yaml, and it returns a Mermaid diagram — a fenced code block, ready to paste straight into a Markdown file. It's a deliberate bridge between this series and my doc-as-code articles: docker-compose-viz and docker-python-mermaid both turn structured data into diagrams with real parsers; ai-diagram handles the case those can't — a description with no schema at all, or a file you don't want to write a parser for just to sketch one diagram.

I've written more "turn X into a diagram" articles than I first realized: Diagrams as code, a graph from compose.yaml, documentation as code with Python and Mermaid. Every one of them shares the same shape: a real parser reads a structured input and a library draws the picture. That works great — right up until what I want to diagram is a paragraph I just typed, or a one-off config file that isn't worth writing a parser for.

Demo — Plain-English Description​

>user@machine: ~/yourproject

No YAML, no schema, just a sentence — and a flowchart that branches on the validation, the one step in that sentence whose outcome decides what happens next, while saving and sending stay plain steps. Pasted into this page, the block renders as:

Demo — An Existing Config File​

>user@machine: ~/yourproject

Three services, their dependency edges, and the named volume — read straight out of the compose file's own structure, with each image and published port folded into its service's label:

Read the Mermaid before you trust it

For anything going into actual documentation — an onboarding doc, an architecture decision record — treat this the same way as docker-compose-viz's output: a strong first draft. The model can miss an edge case (a depends_on: condition: service_healthy, a less obvious network alias) that a real parser like docker-python-mermaid's wouldn't.

More Sentences to Try​

Three more descriptions, each one ready to copy into your own terminal. Every link opens the diagram ai-diagram printed for it, in the Mermaid Live Editor.

Support Ticket Triage​

ai-diagram "When a customer submits a support ticket, check if it is urgent. If it is urgent, assign it directly to a senior agent. If it is not urgent, place it in the standard queue and send an automated confirmation email to the customer."

See the diagram it produces on mermaid.live

Login With a Lockout​

ai-diagram "To log into the system, the user enters their username and password. If the credentials are correct, grant access and display the main dashboard. If the credentials are incorrect, check if the attempt count is less than three. If it is less than three, increment the counter and ask the user to try again. Otherwise, lock the account and send a password reset link to the user's email."

See the diagram it produces on mermaid.live

An E-Commerce Order​

ai-diagram "When receiving an e-commerce order, first verify if the requested item is in stock. If it is out of stock, notify the customer and ask if they want to backorder or cancel. If they cancel, process a full refund. If the item is in stock, check if the payment is processed successfully. If payment fails, prompt the user to update their payment method. If payment succeeds, pack the order, generate a shipping label, ship the item, and send a tracking number to the customer."

See the diagram it produces on mermaid.live

Where This Actually Sits Next to docker-python-mermaid​

Not a replacement — a different job

docker-python-mermaid parses a compose.yaml too, and it is the right tool for a diagram that lives in the documentation: a script written once for that input format, deterministic, regenerated on every change. ai-diagram is for the other half of the job: a Slack message's worth of description, or a format you have no script for — an nginx.conf, a CI workflow, a SQL schema. Less precision, no setup at all — I use both, depending on whether the diagram has to stay in sync or just has to exist by this afternoon.

The ai-diagram Function​

No need to copy anything yet: the .zsh files shown in this article are here to be read, and Installing It at the end creates every one of them in ~/.zsh/fns/ for you.

# ai-diagram <description>|<file> — turn a plain-English description, or an
# existing config/structure file, into a Mermaid diagram. Prints a fenced
# ```mermaid code block, ready to paste into a Markdown file (this blog
# already renders Mermaid natively).
AI_COMMANDS[diagram]="ai-diagram <description>|<file> — turn a description or a config file into a Mermaid diagram"
AI_PARAMS[diagram]="text"
ai-diagram() {
if [[ -z "$1" ]]; then
echo 'Usage: ai-diagram "plain-English description" or ai-diagram <file>' >&2
return 1
fi
local input hint
if [[ -f "$1" ]]; then
input=$(cat "$1")
# Without these rules, a model turns every value it reads into a node of
# its own: "postgres:16" or "8080:80" end up as boxes next to the services.
hint="The input below is the file '$1'. Infer the most natural Mermaid diagram type from its content — a docker-compose.yaml suggests a graph of services and their links, a folder listing suggests a flowchart or tree, an OpenAPI spec suggests a sequence diagram. Follow these rules:
- one node per entity the file declares (a service, a table, a class, a job), labelled with its name and its key attributes, e.g. app[\"app · build · :8080\"];
- one edge per relationship the file states (depends_on, a foreign key, needs), from the entity to what it relies on;
- storage (a named volume, a database file) is a cylinder node, e.g. db_data[(\"db-data\")], linked from the entity that uses it;
- attributes (an image, a port, a type) appear only inside labels, never as nodes of their own;
- node ids use letters, digits and underscores only."
else
input="$*"
hint="The input below is a plain-English description. Pick whichever Mermaid diagram type (flowchart, sequence, ER, class, state) best fits what is being described. Draw every branch the description states. Add a failure branch on your own only where a step is itself a check whose outcome decides what happens next (a validation, a login, a payment) — never for a plain action such as saving, sending or assigning something."
fi
local prompt="You are a Mermaid diagram expert. $hint
Output ONLY a fenced Mermaid code block — no explanation before or after it, no extra commentary, nothing outside the \`\`\`mermaid ... \`\`\` fence.
--- INPUT ---
$input"
local diagram
diagram=$(_ollama_query "$prompt") || return 1
if [[ -z "$diagram" ]]; then
echo "ai-diagram: the model returned an empty answer" >&2
return 1
fi
# The prompt asks for the fence, but a model still adds a sentence before it
# now and then. Keeping only the fenced lines and re-wrapping them makes the
# output paste-ready every time, whatever the model wrapped around it.
local code
code=$(_ai_strip_fences "$diagram")
print -r -- '```mermaid'
print -r -- "$code"
print -r -- '```'
# A Ctrl+click preview on mermaid.live. "base64:" is one of the two formats
# the editor reads from the URL hash — the JSON state, base64url-encoded — so
# jq and coreutils are enough, no compression library. It goes to stderr:
# stdout stays the bare Markdown block, even redirected to a file.
local state
state=$(jq -jcn --arg code "$code" '{code: $code}' | base64 | tr -d '\n=' | tr '+/' '-_')
print -r -- "Preview: https://mermaid.live/edit#base64:${state}" >&2
}

This script takes either a plain-English description or a file path and uses an AI model to generate a Mermaid diagram from it. It sends the input to an AI service with specific instructions about diagram structure, then extracts the fenced code block from the response and prints it in a format ready to paste into Markdown, along with a preview link.

Two input modes, told apart by a single test — if the first argument is an existing file, it's a file:

  1. A file — read as-is, and the prompt asks the model to infer the diagram type from context (a compose.yaml implies a service graph, a folder listing implies a tree, an OpenAPI spec implies a sequence diagram). A short list of rules keeps the graph honest: one node per entity, one edge per relationship, attributes such as an image or a port inside the labels, storage drawn as a cylinder.
  2. Free text — everything after the command is treated as the description, and the model picks whichever Mermaid diagram type fits best on its own, adding a failure branch only where a step is itself a check (a validation, a login, a payment) — never an invented "email sent?" on a plain action.

Either way, the output is a ```mermaid block and nothing else. The prompt asks for exactly that, and _ai_strip_fences then keeps only the fenced lines before the function re-wraps them itself — so even an answer that opens with "Here is your diagram:" comes out ready to paste into a post, where this blog renders it natively.

Before pasting it anywhere, you'll want to see it. The last line, Preview: https://mermaid.live/edit#base64:…, opens the diagram in the Mermaid Live Editor with a Ctrl+click from the terminal — rendered, and editable if the model got a label wrong. The editor reads its whole state from the part of the URL after the #: the JSON {"code": "…"}, base64url-encoded, so jq and base64 are all it takes to build. That fragment is never sent to the server in the request; the diagram is decoded and drawn by the page, in your browser. The link goes to stderr, so ai-diagram compose.yaml > docs/services.md still writes nothing but the Mermaid block.

Registered in the ai Menu​

Two lines — AI_COMMANDS[diagram]=... and AI_PARAMS[diagram]="text" — make it reachable as ai diagram <input> or directly as ai-diagram, alongside every other function in the series. Picked from the bare ai menu, it prompts for its input: type a description, or a file name.

_ollama_query, _ai_strip_fences and the AI_COMMANDS registry all live in the shared _ollama.zsh foundation introduced in ai-test. If you already followed an earlier article in this series, it's already sitting in ~/.zsh/fns/ and sourced by your autoloader — nothing more to do. Starting here instead? It is one of the files created in Installing It below.

Key Takeaways​

ai-diagram quick reference

  • Two input modes — an existing file, or free-text description, auto-detected
  • Diagram type is inferred — flowchart, sequence, ER, class, state — the model picks based on context
  • Output is fence-only — a raw `mermaid block, re-wrapped by the function itself, meant to be pasted directly
  • Ctrl+click to preview — a mermaid.live link on stderr opens the rendered diagram, stdout stays paste-ready
  • Complements, doesn't replace, docker-python-mermaid — a script for diagrams that must stay in sync; this for everything else
  • Registers into ai — reachable as ai diagram

Installing It​

Everything runs on your machine: zsh, curl and jq (which builds the request sent to Ollama), and an Ollama server you can reach — see installing Ollama if you don't have one yet.

1. Create the files. Every function of this series lives in its own file in ~/.zsh/fns/. The one-liner below creates that folder and the two files in one go — or download the ZIP, or create each file by hand and paste its content. _ollama.zsh is the foundation the whole series shares: if an earlier article already gave it to you, the copy here is the same file.

📦 Project setup: ~/.zsh/fns
Help

Need help here? Click the "Help" button above for setup instructions.

2. Load the folder from ~/.zshrc. Already done if you followed an earlier article of this series. Otherwise, add these lines at the end of ~/.zshrc — they source every .zsh file in the folder, so the next function you add needs no change here:

~/.zshrc
for fn_file in ~/.zsh/fns/*.zsh; do
source "$fn_file"
done

3. Open a new terminal (or run exec zsh in the current one), and check that the shell knows the new function:

type ai-diagram

ai-diagram is a shell function from …/ai-diagram.zsh means you're ready. ai-diagram not found means step 2 is missing.

Conclusion​

My doc-as-code articles have always assumed I already had something structured to feed a parser. ai-diagram is what fills the gap before that point — the sentence I just typed, the file I have but haven't written a parser for. It won't replace Diagrams as code or docker-python-mermaid for anything that needs to be exact and reproducible, but for the "let me just sketch this quickly" case that used to mean opening a whiteboard tool, it's turned into one command and a paste.


Was this article helpful?
Did you try the steps in this article?