<!--
  canonical-url: https://www.avonture.be/blog/ollama-ai-diagram
  published:     2026-10-15
  This is a static plain-Markdown mirror generated at build time.
  Visit the canonical URL above for the fully rendered page, with images and interactive components.
-->

# 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.

---
![ai-diagram: From a Sentence (or a compose.yaml) to a Mermaid Diagram](/img/v2/ai_diagram.webp)

**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](/blog/docker-diagram-as-code), [a graph from compose.yaml](/blog/docker-compose-viz), [documentation as code with Python and Mermaid](/blog/docker-python-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

````bash
$ ai-diagram "a user submits a contact form, the API validates the payload, saves it to Postgres, then sends a confirmation email via SMTP"

```mermaid
flowchart TD
    A[User submits contact form] --> B[API validates payload]
    B -->|Validation fails| C[Return validation errors]
    B -->|Validation passes| D[Save to Postgres]
    D --> E[Send confirmation email via SMTP]
    E --> F[Email sent successfully]
```
Preview: https://mermaid.live/edit#base64:eyJjb2RlIjoiZmxvd2NoYXJ0IFREXG4gICAgQVtVc2VyIHN1Ym1pdHMgY29udGFjdCBmb3JtXSAtLT4gQltBUEkgdmFsaWRhdGVzIHBheWxvYWRdXG4gICAgQiAtLT58VmFsaWRhdGlvbiBmYWlsc3wgQ1tSZXR1cm4gdmFsaWRhdGlvbiBlcnJvcnNdXG4gICAgQiAtLT58VmFsaWRhdGlvbiBwYXNzZXN8IERbU2F2ZSB0byBQb3N0Z3Jlc11cbiAgICBEIC0tPiBFW1NlbmQgY29uZmlybWF0aW9uIGVtYWlsIHZpYSBTTVRQXVxuICAgIEUgLS0-IEZbRW1haWwgc2VudCBzdWNjZXNzZnVsbHldIn0
````

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:

```mermaid
flowchart TD
    A[User submits contact form] --> B[API validates payload]
    B -->|Validation fails| C[Return validation errors]
    B -->|Validation passes| D[Save to Postgres]
    D --> E[Send confirmation email via SMTP]
    E --> F[Email sent successfully]
```

## Demo — An Existing Config File

**compose.yaml**

```yaml
services:
  app:
    build: .
    depends_on:
      - db
      - cache
    ports:
      - "8080:80"

  db:
    image: postgres:16
    volumes:
      - db-data:/var/lib/postgresql/data

  cache:
    image: redis:7

volumes:
  db-data:
```

````bash
$ ai-diagram compose.yaml

```mermaid
graph TD
  app["app · build · :8080"]
  db["db · postgres:16"]
  cache["cache · redis:7"]
  db_data[("db-data")]

  app -- "depends_on" --> db
  app -- "depends_on" --> cache
  db -- "volumes" --> db_data
```
Preview: https://mermaid.live/edit#base64:eyJjb2RlIjoiZ3JhcGggVERcbiAgYXBwW1wiYXBwIMK3IGJ1aWxkIMK3IDo4MDgwXCJdXG4gIGRiW1wiZGIgwrcgcG9zdGdyZXM6MTZcIl1cbiAgY2FjaGVbXCJjYWNoZSDCtyByZWRpczo3XCJdXG4gIGRiX2RhdGFbKFwiZGItZGF0YVwiKV1cblxuICBhcHAgLS0gXCJkZXBlbmRzX29uXCIgLS0-IGRiXG4gIGFwcCAtLSBcImRlcGVuZHNfb25cIiAtLT4gY2FjaGVcbiAgZGIgLS0gXCJ2b2x1bWVzXCIgLS0-IGRiX2RhdGEifQ
````

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:

```mermaid
graph TD
  app["app · build · :8080"]
  db["db · postgres:16"]
  cache["cache · redis:7"]
  db_data[("db-data")]

  app -- "depends_on" --> db
  app -- "depends_on" --> cache
  db -- "volumes" --> db_data
```

> **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

```bash
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](https://mermaid.live/edit#base64:eyJjb2RlIjoiZmxvd2NoYXJ0IFREXG4gICAgQVtDdXN0b21lciBzdWJtaXRzIHN1cHBvcnQgdGlja2V0XSAtLT4gQntJcyB0aWNrZXQgdXJnZW50P31cbiAgICBCIC0tIFlFUyAtLT4gQ1tBc3NpZ24gdG8gc2VuaW9yIGFnZW50XVxuICAgIEIgLS0gTk8gLS0-IERbUGxhY2UgaW4gc3RhbmRhcmQgcXVldWVdXG4gICAgRCAtLT4gRVtTZW5kIGF1dG9tYXRlZCBjb25maXJtYXRpb24gZW1haWxdXG4gICAgQyAtLT4gRltFbmRdXG4gICAgRSAtLT4gRltFbmRdIn0)

### Login With a Lockout

```bash
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](https://mermaid.live/edit#base64:eyJjb2RlIjoiZmxvd2NoYXJ0IFREXG4gICAgQVtVc2VyIGVudGVycyB1c2VybmFtZSBhbmQgcGFzc3dvcmRdIC0tPiBCe0NyZWRlbnRpYWxzIGNvcnJlY3Q_fVxuICAgIEIgLS0gWWVzIC0tPiBDW0dyYW50IGFjY2Vzc11cbiAgICBDIC0tPiBEW0Rpc3BsYXkgbWFpbiBkYXNoYm9hcmRdXG4gICAgQiAtLSBObyAtLT4gRXtBdHRlbXB0IGNvdW50IDwgMz99XG4gICAgRSAtLSBZZXMgLS0-IEZbSW5jcmVtZW50IGNvdW50ZXJdXG4gICAgRiAtLT4gR1tBc2sgdXNlciB0byB0cnkgYWdhaW5dXG4gICAgRSAtLSBObyAtLT4gSFtMb2NrIGFjY291bnRdXG4gICAgSCAtLT4gSVtTZW5kIHBhc3N3b3JkIHJlc2V0IGxpbmsgdG8gZW1haWxdIn0)

### An E-Commerce Order

```bash
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](https://mermaid.live/edit#base64:eyJjb2RlIjoiZmxvd2NoYXJ0IFREXG4gICAgQVtSZWNlaXZlIGUtY29tbWVyY2Ugb3JkZXJdIC0tPiBCe0lzIGl0ZW0gaW4gc3RvY2s_fVxuICAgIEIgLS0gTm8gLS0-IENbTm90aWZ5IGN1c3RvbWVyXVxuICAgIEMgLS0-IER7V2FudCB0byBiYWNrb3JkZXIgb3IgY2FuY2VsP31cbiAgICBEIC0tIENhbmNlbCAtLT4gRVtQcm9jZXNzIGZ1bGwgcmVmdW5kXVxuICAgIEQgLS0gQmFja29yZGVyIC0tPiBGW1Byb2NlZWQgd2l0aCBvcmRlcl1cbiAgICBCIC0tIFllcyAtLT4gR3tQYXltZW50IHByb2Nlc3NlZCBzdWNjZXNzZnVsbHk_fVxuICAgIEcgLS0gTm8gLS0-IEhbUHJvbXB0IHVzZXIgdG8gdXBkYXRlIHBheW1lbnQgbWV0aG9kXVxuICAgIEggLS0-IEdcbiAgICBHIC0tIFllcyAtLT4gSVtQYWNrIG9yZGVyXVxuICAgIEkgLS0-IEpbR2VuZXJhdGUgc2hpcHBpbmcgbGFiZWxdXG4gICAgSiAtLT4gS1tTaGlwIGl0ZW1dXG4gICAgSyAtLT4gTFtTZW5kIHRyYWNraW5nIG51bWJlciB0byBjdXN0b21lcl0ifQ)

## Where This Actually Sits Next to `docker-python-mermaid`

> **Not a replacement — a different job:**
>
> [`docker-python-mermaid`](/blog/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](#installing-it) at the end creates every one of them in `~/.zsh/fns/` for you.

**\~/.zsh/fns/ai-diagram.zsh**

````bash
# 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
}
````

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](https://mermaid.live) 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](/blog/ollama-test-generator). 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](#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](/blog/ollama-installation) 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: \~/.zsh/fns**

**\_ollama.zsh**

````bash
# Foundation file for every "ai-*" function in this series. Named with a
# leading underscore: the ~/.zsh/fns/*.zsh loader sources files in
# alphabetical order, and "_" sorts before any letter — so this file is
# always loaded first, no matter how many ai-* functions get added later.
#
# Provides:
#   - _ollama_check       reachability guard for Ollama
#   - _ollama_query       shared HTTP client (curl + jq)
#   - _ai_strip_fences    removes the Markdown fences models add anyway
#   - _ai_bat             resolves "bat" vs Debian's "batcat"
#   - _ai_confirm         yes/no prompt
#   - _git_staged_diff    validated staged-diff fetcher (shared by pre-commit functions)
#   - AI_COMMANDS         registry each ai-* function adds itself to
#   - AI_PARAMS           registry of interactive parameter types (file/language/number/text/none)
#   - _ai_prompt_*        FZF/read helpers for interactive argument collection
#   - ai                  entry-point dispatcher / interactive menu

typeset -gA AI_COMMANDS
typeset -gA AI_PARAMS

# ---------------------------------------------------------------------------
# Ollama helpers
# ---------------------------------------------------------------------------

# _ollama_check — verify that the Ollama daemon is reachable.
# Fails loudly so callers can bail early rather than watching curl hang.
_ollama_check() {
  local host="${OLLAMA_HOST:-http://localhost:11434}"
  if ! curl --silent --max-time 2 "${host}/api/tags" >/dev/null 2>&1; then
    echo "ollama: cannot reach ${host} — is the Ollama container running?" >&2
    return 1
  fi
}

# _ollama_query <prompt> — send a prompt to the local model and print the response.
# Assumes Ollama is reachable; call _ollama_check first if you need an early guard.
_ollama_query() {
  local prompt="$1"
  local model="${OLLAMA_MODEL:-qwen3-coder:30b}"
  local host="${OLLAMA_HOST:-http://localhost:11434}"

  _ollama_check || return 1

  # The prompt is piped into jq rather than passed with "--arg": Linux caps a
  # single argv entry at 128 KB (MAX_ARG_STRLEN), and a large staged diff or a
  # long source file sails straight through that ceiling — jq then dies with
  # "argument list too long". "-R -s" slurps stdin as one raw string, which jq
  # escapes exactly like --arg would.
  print -r -- "$prompt" \
    | jq -Rs --arg model "$model" '{model: $model, prompt: ., stream: false}' \
    | curl --silent "${host}/api/generate" --data-binary @- \
    | jq -r '.response // empty'
}

# ---------------------------------------------------------------------------
# Output helpers
# ---------------------------------------------------------------------------

# _ai_strip_fences <text> — return only the code, without the Markdown fences.
#
# Every prompt in this series ends with "no markdown fences" and models still
# wrap their answer in ```language … ``` often enough that the output can't be
# piped or pasted as-is. When at least one fence is present, only the fenced
# regions are kept (which also drops the "Here is your test suite:" preamble);
# when there is none, the text is returned untouched.
_ai_strip_fences() {
  local text="$1"

  if [[ "$text" != *'```'* ]]; then
    print -r -- "$text"
    return 0
  fi

  print -r -- "$text" | awk '
    /^[[:space:]]*```/ { inside = !inside; next }
    inside             { print }
  '
}

# _ai_bat — print the name of the "bat" binary installed on this machine, if any.
# Debian and Ubuntu ship the package as "batcat" because the "bat" name was
# already taken by bacula-console-qt, so both spellings have to be probed.
_ai_bat() {
  local candidate
  for candidate in bat batcat; do
    if command -v "$candidate" >/dev/null 2>&1; then
      print -- "$candidate"
      return 0
    fi
  done
  return 1
}

# _ai_relpath <path> — print <path> relative to the current folder when it sits
# below it. Purely cosmetic: it keeps prompts readable instead of asking
# "Save as /home/christophe/projects/…/tests/backup.bats?".
_ai_relpath() {
  local path="${1:A}"
  print -- "${path#${PWD}/}"
}

# _ai_confirm <question> — ask a yes/no question; return 0 only on an explicit yes.
_ai_confirm() {
  local answer
  print -n "${1} [y/N] "
  read -r answer
  [[ "$answer" == [yY]* ]]
}

# ---------------------------------------------------------------------------
# Git helpers
# ---------------------------------------------------------------------------

# _git_staged_diff <caller> — validate the git context and return the staged diff.
# Handles three early-exit cases (not a repo, nothing staged, oversized diff)
# so every pre-commit function gets them for free without repeating the guards.
#
# Past AI_DIFF_MAX_CHARS the full diff is *not* returned: a diff of several
# hundred kilobytes overflows the model's context window, and the answer that
# comes back is worse than the one you get from a summary. The fallback keeps
# the shape of the change — per-file stat, plus the file and hunk headers,
# which carry the enclosing function names git puts after each "@@" — and
# drops the line-by-line content.
_git_staged_diff() {
  local caller="${1:-ai}"
  local max="${AI_DIFF_MAX_CHARS:-12000}"

  if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
    echo "${caller}: not inside a git repository" >&2
    return 1
  fi

  local diff
  diff=$(git diff --staged)

  if [[ -z "$diff" ]]; then
    echo "${caller}: nothing staged — run 'git add' first" >&2
    return 1
  fi

  # "print -r" everywhere below: without it, print expands escape sequences and
  # a literal \n or \t inside the diff would come back mangled.
  if (( ${#diff} <= max )); then
    print -r -- "$diff"
    return 0
  fi

  echo "${caller}: staged diff is large (${#diff} chars) — sending a structural summary instead of the full diff. Commit in smaller chunks for a more precise answer." >&2

  local summary
  summary="$(git diff --staged --stat)

--- FILE AND HUNK HEADERS ONLY (full diff omitted, ${#diff} chars) ---
$(print -r -- "$diff" | grep -E '^(diff --git|new file|deleted file|rename (from|to)|@@)')"

  # Even the summary can exceed the ceiling on a very wide change.
  if (( ${#summary} > max )); then
    summary="${summary[1,$max]}
[…summary truncated…]"
  fi

  print -r -- "$summary"
}

# ---------------------------------------------------------------------------
# Interactive argument helpers (used by the ai() dispatcher)
# ---------------------------------------------------------------------------

# _ai_prompt_file [label] — open an fzf file picker; print the chosen path.
_ai_prompt_file() {
  local label="${1:-Select a file:}"
  local bat_bin preview='cat {}'
  bat_bin=$(_ai_bat) && preview="${bat_bin} --color=always {} 2>/dev/null || cat {}"

  if command -v fd >/dev/null 2>&1; then
    fd --type f | fzf --prompt="${label} " --height=50% --reverse --preview="$preview"
  else
    find . -type f | fzf --prompt="${label} " --height=50% --reverse --preview="$preview"
  fi
}

# _ai_prompt_language — open an fzf language picker; print the chosen language.
_ai_prompt_language() {
  printf '%s\n' English French Dutch German Spanish Italian Portuguese Japanese Chinese Korean \
    | fzf --prompt='Target language: ' --height=40% --reverse
}

# _ai_prompt_number [label] — read a positive integer; print it (or nothing on Enter, which
# lets the caller fall back to its own default). Returns 1 only on invalid input.
_ai_prompt_number() {
  local label="${1:-Number (Enter for default):}"
  print -n "${label} "
  local n
  read n
  if [[ -z "$n" ]]; then
    return 0
  fi
  if [[ ! "$n" =~ ^[1-9][0-9]*$ ]]; then
    echo "Expected a positive integer." >&2
    return 1
  fi
  print -- "$n"
}

# _ai_prompt_text [label] — read a free-form string; print it. Returns 1 if empty.
_ai_prompt_text() {
  local label="${1:-Input:}"
  print -n "${label} "
  local t
  read t
  if [[ -z "$t" ]]; then
    echo "No input given." >&2
    return 1
  fi
  print -- "$t"
}

# ---------------------------------------------------------------------------
# Entry-point dispatcher
# ---------------------------------------------------------------------------

# ai              → interactive fzf menu of every registered ai-* command
# ai <cmd> [args] → dispatch straight to ai-<cmd> [args]
#
# When opened via the fzf menu, each command's declared AI_PARAMS type triggers
# a secondary picker before the command runs:
#   file     → fzf file picker (fd + preview if available)
#   language → fzf language list
#   number   → read prompt, empty input uses the command's own default
#   text     → read prompt, required
#   none     → run the command directly (it collects its own input)
# Space-separated values declare multiple parameters in order, e.g. "file language".
ai() {
  local cmd="$1"

  # Direct dispatch: ai <cmd> [args]
  if [[ -n "$cmd" && "$cmd" != "help" && "$cmd" != "list" ]]; then
    if (( ${+AI_COMMANDS[$cmd]} )); then
      shift
      "ai-${cmd}" "$@"
      return
    fi
    echo "ai: unknown command '${cmd}'" >&2
    echo >&2
  fi

  # Interactive menu
  if ! command -v fzf >/dev/null 2>&1; then
    echo "Available ai commands:"
    for key in ${(ok)AI_COMMANDS}; do
      printf "  ai %-10s %s\n" "$key" "$AI_COMMANDS[$key]"
    done
    return
  fi

  local picked
  picked=$(
    for key in ${(ok)AI_COMMANDS}; do
      printf '%s\t%s\n' "$key" "$AI_COMMANDS[$key]"
    done \
      | fzf --delimiter='\t' --with-nth=2 --prompt='ai > ' --height=40% --reverse \
      | cut -f1
  )
  [[ -z "$picked" ]] && return

  # Collect arguments interactively based on AI_PARAMS declaration
  local -a args=()
  local param_type
  for param_type in ${(s: :)${AI_PARAMS[$picked]:-none}}; do
    case "$param_type" in
      file)
        local f
        f=$(_ai_prompt_file "File for ai-${picked}:") || return 1
        args+=("$f")
        ;;
      language)
        local l
        l=$(_ai_prompt_language) || return 1
        args+=("$l")
        ;;
      number)
        local n
        n=$(_ai_prompt_number) || return 1
        [[ -n "$n" ]] && args+=("$n")
        ;;
      text)
        local t
        t=$(_ai_prompt_text) || return 1
        args+=("$t")
        ;;
      none) ;;
    esac
  done

  "ai-${picked}" "${args[@]}"
}
````

**ai-diagram.zsh**

````bash
# 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
}
````

**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:

```zsh title="~/.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:

```zsh
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](/blog/docker-diagram-as-code) or [docker-python-mermaid](/blog/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.
