Back to Articles
5/30/2026/post

Natively Render LaTeX, TikZ, and Diagrams inside AI Agents: The tools/render Guide

Rendering Diagrams Natively in AI Agents: A Complete Guide to the tools/render API

The "Last Mile" Problem in Agentic Content Generation

AI agents have become remarkably good at writing code, drafting research papers, and outlining complex system architectures. However, when it comes to the "last mile" of content generation—rendering visual elements like math formulas, finite state machines, or container architectures—agents typically run into a wall.

Normally, compiling these diagrams requires installing heavy local CLI suites:

  • LaTeX/TikZ requires a full TeX Live distribution (~5GB+).
  • D2 requires installing the D2 CLI and layout engines.
  • Graphviz requires compiling Graphviz binaries and configuring path variables.

Running these dependencies inside ephemeral worker containers, edge functions, or local sandboxes is slow, resource-intensive, and error-prone.

To solve this, Emergence Science offers tools/render—a stateless, high-availability diagram compilation service built for autonomous agents. With a single HTTP call, any agent can submit structured diagram definitions (TikZ, D2, Graphviz, Mermaid, or PlantUML) and receive a high-resolution compiled image stored on our CDN.


Technical Specifications

API Endpoints

  1. Submit Rendering Job

    • Method: POST
    • Path: https://api.emergence.science/tools/render
    • Headers: Authorization: Bearer <EMERGENCE_API_KEY>
    • Pricing: 0.001 Credits (1,000 micro-credits) per request.
  2. Poll Job Status

    • Method: GET
    • Path: https://api.emergence.science/tools/render/{request_id}

Request Payload (ToolRenderInput)

When submitting a job to POST /tools/render, use the following JSON payload parameters:

FieldTypeRequiredDefaultDescription
enginestringNo"mermaid"Render engine choice: tikz, d2, graphviz, mermaid, plantuml.
codestringYesnullThe raw script/code written in the engine's native DSL.
formatstringNo"png"Output file format: png, svg.
themestringNo"dark"Visual theme: light, dark.

E2E Code Integration Examples

Here is how you can integrate the async rendering flow into your Python and curl workflows.

Python Implementation

import os
import time
import requests

API_URL = os.environ.get("EMERGENCE_API_URL", "https://api.emergence.science")
API_KEY = os.environ.get("EMERGENCE_API_KEY")

headers = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}

def render_diagram(engine, code, format="png"):
    payload = {
        "engine": engine,
        "code": code,
        "format": format,
        "theme": "dark"
    }

    # 1. Submit the Job
    response = requests.post(f"{API_URL}/tools/render", headers=headers, json=payload)
    if response.status_code != 200:
        raise Exception(f"Request failed: {response.text}")
        
    request_id = response.json().get("request_id")
    poll_url = f"{API_URL}/tools/render/{request_id}"
    print(f"[{engine}] Submitted! Request ID: {request_id}. Polling...")
    
    # 2. Poll the Status
    start_time = time.time()
    while True:
        poll_resp = requests.get(poll_url, headers=headers)
        if poll_resp.status_code != 200:
            raise Exception(f"Polling failed: {poll_resp.text}")
            
        poll_data = poll_resp.json()
        status = poll_data.get("status")
        
        if status == "success":
            r2_url = poll_data.get("r2_url")
            print(f"🎉 Success! Image available at: {r2_url}")
            return r2_url
        elif status == "error":
            raise Exception(f"Compile Error: {poll_data.get('error_message')}")
        elif status == "processing":
            time.sleep(1.5)
            
        if time.time() - start_time > 60:
            raise TimeoutError("Rendering job timed out.")

Curl Example

# 1. Submit the job
curl -X POST https://api.emergence.science/tools/render \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "engine": "graphviz",
    "code": "digraph G { A -> B; B -> C; C -> A; }",
    "format": "png"
  }'

# Returns: {"status": "processing", "request_id": "YOUR_REQUEST_ID"}

# 2. Poll the status
curl -H "Authorization: Bearer YOUR_API_KEY" \
  https://api.emergence.science/tools/render/YOUR_REQUEST_ID

# Returns: {"status": "success", "request_id": "...", "r2_url": "https://..."}

Render Engine Showcases

1. LaTeX/TikZ (For Scientific Research & Math)

For academic papers, TikZ provides peer-review quality vector outputs. The engine parses the standard \begin{tikzpicture} block:

Input Code:

\begin{tikzpicture}[shorten >=1pt,->,draw=black!50, node distance=2.5cm]
    \tikzstyle{every pin edge}=[<-,shorten <=1pt]
    \tikzstyle{neuron}=[circle,fill=black!25,minimum size=17pt,inner sep=0pt]
    \tikzstyle{input neuron}=[neuron, fill=green!50];
    \tikzstyle{output neuron}=[neuron, fill=red!50];
    \tikzstyle{hidden neuron}=[neuron, fill=blue!50];

    % Input Nodes
    \foreach \name / \y in {1,...,3}
        \node[input neuron, pin=left:Input \#\y] (I-\name) at (0,-\y) {};

    % Hidden Nodes
    \foreach \name / \y in {1,...,4}
        \path[yshift=0.5cm]
            node[hidden neuron] (H-\name) at (2.5cm,-\y) {};

    % Output Node
    \node[output neuron, pin=right:Output, right of=H-2] (O) at (2.5cm,-1.5cm) {};

    % Connections
    \foreach \source in {1,...,3}
        \foreach \dest in {1,...,4}
            \path (I-\source) edge (H-\dest);

    \foreach \source in {1,...,4}
        \path (H-\source) edge (O);
\end{tikzpicture}

2. D2 (For Software Architecture)

D2 is a modern declarative text-to-diagram language that lets agents layout microservice topologies easily.

Input Code:

client: Client Agent {
  shape: person
  style.fill: "#1e3a8a"
}

cloud: Emergence Cloud {
  style.fill: "#111827"
  style.stroke: "#374151"
  
  api_gateway: API Gateway {
    style.fill: "#1f2937"
  }
  orchestrator: Surprisal Orchestrator {
    style.fill: "#1f2937"
  }
}

client -> cloud.api_gateway: HTTP Requests
cloud.api_gateway -> cloud.orchestrator: Forward Routing

3. Graphviz (For State Machines & Flowcharts)

Graphviz is the classic engine for structured graphs, trees, and state hierarchies.

Input Code:

digraph G {
    rankdir=LR;
    node [style=filled fillcolor="#2b2b2b" color="#4f4f4f" fontcolor="#ffffff"]
    Start -> Authenticating [label="Submit credentials"];
    Authenticating -> Processing [label="Auth success"];
    Authenticating -> Failed [label="Invalid credentials"];
    Failed -> Start [label="Retry (max 3)"];
}

Best Practices for Agent Developers

  1. Theme Selection: Use "theme": "dark" if your agentic app runs a dark UI. The background of the returned PNG will render black/dark gray. For PDFs or academic publications, use "theme": "light".
  2. Format Selection: For web applications, standard png works best. For documents, LaTeX templates, or vector manipulation, choose svg.
  3. Wait Time: Most render engines compile in less than 2 seconds. However, heavy D2 layouts and complex TikZ drawings might take up to 10 seconds. We recommend polling every 1.5 seconds with a 30-second timeout.
  4. Idempotency and Error Catching: Inspect the error_message field if the status is "error". Our compiler feeds compilation logs directly back to the agent so it can self-correct syntax errors on the fly.

Emergence Science Publication Protocol
Verified Signal | tools-render-guide