Skip to content

tools.kroki

HTTP clients and helpers for each rendering backend. The diagram pipeline tries Kroki first; the other modules implement fallback paths.

tools.kroki.kroki

tools.kroki.kroki

Kroki client library for Python.

This library allows generating diagrams using the Kroki service. Kroki is a unified API for generating diagrams from textual descriptions.

KrokiError

Bases: Exception

Base exception for Kroki errors.

KrokiConnectionError

Bases: KrokiError

Error connecting or talking to Kroki Service.

KrokiHTTPError

KrokiHTTPError(response: Response, content: str | bytes)

Bases: KrokiError

Request to Kroki server returned HTTP Error.

Kroki

Kroki(base_url: str = 'https://kroki.io', **http_opts: Any)

Client for the Kroki diagram generation service.

Kroki provides a unified API for generating diagrams from textual descriptions. This client supports multiple diagram types including PlantUML, Mermaid, D2, and more.

Attributes:

Name Type Description
base_url

The base URL of the Kroki service.

client

The HTTP client for making requests.

Initialize the Kroki client.

Parameters:

Name Type Description Default
base_url str

The base URL of the Kroki service.

'https://kroki.io'
**http_opts Any

Additional options to pass to the httpx client.

{}

get_url

get_url(
    diagram_type: str,
    diagram_text: str,
    output_format: str = "svg",
) -> str

Generate the URL for a diagram.

Parameters:

Name Type Description Default
diagram_type str

The type of diagram (plantuml, mermaid, etc.)

required
diagram_text str

The textual description of the diagram

required
output_format str

The desired output format (svg, png, etc.)

'svg'

Returns:

Type Description
str

The URL where the diagram can be accessed

Raises:

Type Description
ValueError

If the diagram type or output format is not supported

get_playground_url

get_playground_url(
    diagram_type: str, diagram_text: str
) -> Optional[str]

Generate a URL to an online playground for editing the diagram.

Parameters:

Name Type Description Default
diagram_type str

The type of diagram (plantuml, mermaid, etc.)

required
diagram_text str

The textual description of the diagram

required

Returns:

Type Description
Optional[str]

A URL to an online playground or None if not available

render_diagram

render_diagram(
    diagram_type: str,
    diagram_text: str,
    output_format: str = "svg",
) -> bytes

Render a diagram and return the image data.

Parameters:

Name Type Description Default
diagram_type str

The type of diagram (plantuml, mermaid, etc.)

required
diagram_text str

The textual description of the diagram

required
output_format str

The desired output format (svg, png, etc.)

'svg'

Returns:

Type Description
bytes

The binary content of the rendered diagram

Raises:

Type Description
KrokiHTTPError

If there was an HTTP error

KrokiConnectionError

If there was a connection error

generate_diagram

generate_diagram(
    diagram_type: str,
    diagram_text: str,
    output_format: str = "svg",
) -> Dict

Generate a diagram and return URLs and data.

Parameters:

Name Type Description Default
diagram_type str

The type of diagram (plantuml, mermaid, etc.)

required
diagram_text str

The textual description of the diagram

required
output_format str

The desired output format (svg, png, etc.)

'svg'

Returns:

Type Description
Dict

A dictionary containing:

Dict
  • url: The URL where the diagram can be accessed
Dict
  • content: The binary content of the rendered diagram
Dict
  • playground: URL to an online playground (if available)

Raises:

Type Description
KrokiHTTPError

If there was an HTTP error

KrokiConnectionError

If there was a connection error

deflate_and_encode

deflate_and_encode(text: str) -> str

Compress the text with zlib and encode it for the Kroki server.

Parameters:

Name Type Description Default
text str

The text to compress and encode

required

Returns:

Type Description
str

The compressed and encoded text

encode_plantuml

encode_plantuml(text: str) -> str

Encode text for PlantUML server.

Parameters:

Name Type Description Default
text str

The PlantUML diagram text

required

Returns:

Type Description
str

The encoded text suitable for PlantUML server URLs

scale_svg

scale_svg(svg_bytes: bytes, scale: float) -> bytes

Scale an SVG by multiplying root width/height attributes.

Only affects SVG output; use when output_format is svg and scale != 1.0. Minimum scale 0.1. Width and height are scaled; viewBox is left unchanged so the graphic fills the new size.

Parameters:

Name Type Description Default
svg_bytes bytes

Raw SVG document bytes (UTF-8).

required
scale float

Multiplier for width and height (e.g. 2.0 doubles size).

required

Returns:

Type Description
bytes

New SVG bytes with scaled width/height.

plantuml_playground_path_segment

plantuml_playground_path_segment(encoded: str) -> str

Normalize the path segment after /plantuml/uml/ for plantuml.com.

A leading ~1 marks Huffman-compressed payloads on plantuml.com (https://plantuml.com/text-encoding). This codebase uses DEFLATE plus PlantUML's 6-bit alphabet (no ~1). Strip a mistaken prefix so the web editor decodes the diagram instead of showing a Huffman error.

generate_kroki_url

generate_kroki_url(
    diagram_type: str,
    diagram_source: str,
    output_format: str = "svg",
) -> str

Generate a URL for the Kroki diagram

Parameters:

Name Type Description Default
diagram_type str

Type of diagram (e.g., "plantuml", "mermaid")

required
diagram_source str

Source code for the diagram

required
output_format str

Output format (e.g., "svg", "png")

'svg'

Returns:

Type Description
str

URL for the diagram

generate_diagram async

generate_diagram(
    diagram_type: str,
    diagram_source: str,
    output_format: str = "svg",
) -> Tuple[str, str, str]

Generate a diagram using Kroki API

Parameters:

Name Type Description Default
diagram_type str

Type of diagram (e.g., "plantuml", "mermaid")

required
diagram_source str

Source code for the diagram

required
output_format str

Output format (e.g., "svg", "png")

'svg'

Returns:

Type Description
Tuple[str, str, str]

Tuple of (url, content, playground_url)

tools.kroki.plantuml

tools.kroki.plantuml

PlantUML client library.

This library allows you to connect to a PlantUML server and render PlantUML markup into PNG images.

PlantUMLError

Bases: Exception

Error in processing.

PlantUMLConnectionError

Bases: PlantUMLError

Error connecting or talking to PlantUML Server.

PlantUMLHTTPError

PlantUMLHTTPError(response: Response, content: str)

Bases: PlantUMLError

Request to PlantUML server returned HTTP Error.

PlantUML

PlantUML(
    url: str,
    basic_auth: Optional[Dict] = None,
    form_auth: Optional[Dict] = None,
    http_opts: Optional[Dict] = None,
    request_opts: Optional[Dict] = None,
)

Connection to a PlantUML server with optional authentication.

Initialize the PlantUML client.

Parameters:

Name Type Description Default
url str

URL to the PlantUML server image CGI

required
basic_auth Optional[Dict]

Dictionary containing username and password for basic HTTP auth

None
form_auth Optional[Dict]

Dictionary for cookie based webform login authentication

None
http_opts Optional[Dict]

Extra options for the HTTP client

None
request_opts Optional[Dict]

Extra options for HTTP requests

None

get_url

get_url(plantuml_text)

Return the server URL for the image.

process

process(plantuml_text: str)

Process the plantuml text and return the URL and content.

deflate_and_encode

deflate_and_encode(plantuml_text)

Compress and encode the plantuml text.

encode

encode(data: bytes)

Encode the plantuml data.

generate_image_from_string

generate_image_from_string(
    plantuml_text: str,
) -> Tuple[str, str, str]

Generate an image from plantuml markup and return URLs.

Parameters:

Name Type Description Default
plantuml_text str

The PlantUML markup text

required

Returns:

Type Description
Tuple[str, str, str]

Tuple of (image_url, content_text, playground_url)

Raises:

Type Description
PlantUMLHTTPError

If there was an error processing the diagram

tools.kroki.mermaid

tools.kroki.mermaid

Mermaid diagram URL and state serialization.

Provides encoding compatible with mermaid.ink (image URLs) and mermaid.live (editor URLs) using pako/base64 state.

MermaidUrls dataclass

MermaidUrls(image_url: str, edit_url: str, code: str)

URLs and code for a Mermaid diagram (image, editor, and source).

image_url instance-attribute

image_url: str

URL to the rendered SVG image (mermaid.ink).

edit_url instance-attribute

edit_url: str

URL to open the diagram in mermaid.live editor.

code instance-attribute

code: str

The Mermaid diagram source code.

Serde

Base class for state serialization/deserialization (e.g. pako, base64).

PakoSerde

Bases: Serde

Pako-compatible deflate serialization (used by mermaid.live).

serialize_state

serialize_state(
    state: dict[str, Any], serde: str = "pako"
) -> str

Serialize a Mermaid editor state dict to a string for use in URLs.

Parameters:

Name Type Description Default
state dict[str, Any]

State dict with at least "code" and optionally "mermaid" theme.

required
serde str

"pako" (default) or "base64".

'pako'

Returns:

Type Description
str

String in the form "serde:payload" for mermaid.ink / mermaid.live URLs.

deserialize_state

deserialize_state(state: str) -> dict[str, Any]

Deserialize a state string back to a dict.

generate_diagram_state

generate_diagram_state(
    diagram_text: str,
    theme: str = "default",
    *,
    update_editor: bool = True,
    auto_sync: bool = True,
    update_diagram: bool = True,
) -> dict[str, Any]

Build the state dict used by mermaid.live / mermaid.ink.

generate_mermaid_urls

generate_mermaid_urls(
    diagram_state: dict[str, Any] | None = None,
    diagram_text: str | None = None,
    theme: str = "default",
    serde: str = "pako",
    image_format: str = "svg",
) -> MermaidUrls

Generate image and editor URLs for a Mermaid diagram.

Either pass diagram_state (full state dict) or diagram_text (and optional theme). If both are provided, diagram_state takes precedence.

get_image_url

get_image_url(
    diagram_text: str,
    theme: str = "default",
    image_format: str = "svg",
) -> str

Return the mermaid.ink image URL for the given diagram code.

get_edit_url

get_edit_url(
    diagram_text: str, theme: str = "default"
) -> str

Return the mermaid.live editor URL for the given diagram code.

generate_mermaid_live_editor_url

generate_mermaid_live_editor_url(
    diagram_state: dict[str, Any], serde: str = "pako"
) -> MermaidUrls

Generate image and editor URLs from a state dict. Prefer generate_mermaid_urls.

tools.kroki.d2

tools.kroki.d2

tools.kroki.tikz

tools.kroki.tikz

TikZ diagram URL generation, template library, and LaTeX utilities.

Provides TikZ/PGF graphics support via Kroki: URL generation, standalone document wrapping, library auto-detection, and pre-built templates.

TikZUrls dataclass

TikZUrls(image_url: str, edit_url: str | None, code: str)

URLs and code for a TikZ diagram (image, optional editor, source).

image_url instance-attribute

image_url: str

URL to the rendered diagram (Kroki).

edit_url instance-attribute

edit_url: str | None

URL to open in an online editor (Overleaf) or None if not available.

code instance-attribute

code: str

The TikZ/LaTeX source code.

TikZTemplateLibrary

Pre-built TikZ templates for common diagram patterns.

get classmethod

get(name: str) -> str

Return a template by name. Names: flowchart, graph, math_plot, tree, automata, geometry_circle, mindmap_simple, circuit_simple, coordinate_grid, block_diagram.

list_names classmethod

list_names() -> List[str]

Return list of available template names.

get_required_libraries

get_required_libraries(tikz_code: str) -> List[str]

Infer required TikZ libraries from diagram code.

Scans for \usetikzlibrary{...} and common commands/styles that imply specific libraries. Returns a deduplicated list of library names.

Parameters:

Name Type Description Default
tikz_code str

Raw TikZ or full LaTeX document content.

required

Returns:

Type Description
List[str]

List of TikZ library names (e.g. ['shapes', 'arrows', 'positioning']).

wrap_tikz_standalone

wrap_tikz_standalone(
    tikz_code: str,
    libraries: List[str] | None = None,
    *,
    border: str = "2pt",
    extra_packages: List[str] | None = None,
) -> str

Wrap TikZ snippet in a minimal standalone LaTeX document.

If the code already contains \documentclass, it is returned unchanged. Otherwise wraps in standalone with tikz and optional libraries.

Parameters:

Name Type Description Default
tikz_code str

TikZ picture or full document.

required
libraries List[str] | None

TikZ libraries to load (default: auto-detect from code).

None
border str

Standalone border option (e.g. '2pt', '10pt').

'2pt'
extra_packages List[str] | None

Additional \usepackage{...} to add (e.g. ['pgfplots']).

None

Returns:

Type Description
str

Full LaTeX document string.

generate_tikz_urls

generate_tikz_urls(
    tikz_code: str,
    output_format: str = "svg",
    base_url: str = "https://kroki.io",
    *,
    wrap_standalone: bool = True,
    include_edit_url: bool = True,
) -> TikZUrls

Generate Kroki image URL and optional edit URL for a TikZ diagram.

Parameters:

Name Type Description Default
tikz_code str

TikZ/LaTeX code (snippet or full document).

required
output_format str

One of 'svg', 'pdf', 'png', 'jpeg'.

'svg'
base_url str

Kroki server base URL.

'https://kroki.io'
wrap_standalone bool

If True, wrap snippet in standalone document when needed.

True
include_edit_url bool

If True, set edit_url to Overleaf data-URI link when possible.

True

Returns:

Type Description
TikZUrls

TikZUrls with image_url, edit_url (or None), and normalized code.

Raises:

Type Description
ValueError

If output_format is not supported for TikZ.

tools.kroki.kroki_templates

tools.kroki.kroki_templates

Templates and examples for various diagram formats supported by Kroki.

DiagramExamples

Provides complete examples for different diagram formats supported by Kroki.

get_example staticmethod

get_example(diagram_type: str) -> str

Get a comprehensive example for the specified diagram type.

Parameters:

Name Type Description Default
diagram_type str

The type of diagram (plantuml, mermaid, etc.)

required

Returns:

Type Description
str

A comprehensive example for the diagram type

DiagramTemplates

Provides starter templates for different diagram formats.

get_template staticmethod

get_template(diagram_type: str) -> str

Get a starter template for the specified diagram type.

Parameters:

Name Type Description Default
diagram_type str

The type of diagram (plantuml, mermaid, etc.)

required

Returns:

Type Description
str

A starter template for the diagram type