Skip to content

Docs

Agent quickstart: give your agent a generate_pdf tool

Give any function-calling agent a generate_pdf tool: a JSON Schema, a server-side executor that sends HTML or template data, document references and errors.

Updated 16 min readSublimePDF Team

This quickstart gives an AI agent one tool, generate_pdf, that turns HTML, or the ID of a template saved in SublimePDF plus JSON data, into a PDF. It works with any model API or agent framework that supports tool calling, also called function calling. You need no MCP server, no SDK and no framework-specific plugin: a JSON Schema, about 150 lines of executor code on your server, and an API key.

The pattern is the same in every framework. The model decides when a document is needed and fills in the arguments. Your code validates them, calls SublimePDF with the key it holds, stores the PDF and gives the model a short reference to the file. The model never sees the key or the PDF bytes.

How the pieces fit

  1. You register the generate_pdf tool (name, description, JSON Schema) with your model API.
  2. The model replies with a tool call, either {"html": "<!doctype html>..."} or {"template_id": "invoice", "data": {...}}.
  3. Your executor validates the arguments, then sends POST /html-to-pdf or POST /templates/invoice/generate with Authorization: Bearer and an Idempotency-Key.
  4. SublimePDF returns application/pdf. The executor saves it wherever your application keeps files.
  5. The executor returns a small JSON document reference (ID, file name, size, page count, hash) as the tool result.
  6. The model tells the user the document is ready, or corrects its arguments if the tool returned an error.

The complete files are published as downloads: generate-pdf-tool.ts (Node.js 22.18 or later, no dependencies), generate_pdf_tool.py (Python 3.9 or later, standard library only), agent-loop-claude.ts (a complete agent loop for one model API), mock-server.mjs, a local mock of the documented API for testing without a key, and package.json, which marks the folder as ES modules. The excerpts below are taken from those files.

Before you start

  • Create an account and an API key. Keys are created in the app under Settings → API keys. Store the key in your server's secret manager or environment as SUBLIMEPDF_API_KEY.
  • Choose the input your agent will send. HTML needs nothing else: the model, or your code, supplies a complete HTML document. If you would rather the agent fill a fixed layout, save a template in the app (start from the invoice template or report template, or your own) and note its ID. Both HTML with data and saved templates use Handlebars-compatible placeholders such as {{customer.name}} and {{#each items}}; the template variables guide covers the syntax.
  • Decide where PDFs go. The API returns the PDF bytes. Your executor decides where they live: a local folder in development, object storage or your database in production.

Step 1: Define the tool

This is the tool definition from the example files. It is plain JSON Schema, so it is not tied to any one provider.

{
  "name": "generate_pdf",
  "description": "Create a PDF with SublimePDF and save it on the server. It accepts two kinds of input; provide exactly one of html or template_id. html: a complete HTML document with its CSS, written for this request; optional data fills {{placeholders}} in it. template_id with data: fill a template saved in the SublimePDF app; use it when you have been given a template ID, never guess one, and send data whose keys match that template's fields. Values are printed as given: calculate totals and format dates and currency before calling. Returns a document reference (id, file name, size, pages), never the PDF content itself.",
  "parameters": {
    "type": "object",
    "properties": {
      "template_id": {
        "type": "string",
        "description": "ID of a template saved in the SublimePDF app, as given by the user or system prompt, e.g. \"invoice\". Omit when sending html.",
        "pattern": "^[A-Za-z0-9_-]{1,64}$"
      },
      "data": {
        "type": "object",
        "description": "Values for the placeholders in the template or HTML. Keys must match the placeholder names. Required with template_id; optional with html."
      },
      "html": {
        "type": "string",
        "description": "Complete HTML document to render, including its CSS. Omit when sending template_id.",
        "maxLength": 200000
      },
      "filename": {
        "type": "string",
        "description": "Optional output file name without directories, e.g. \"invoice-1042.pdf\".",
        "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]{0,95}$"
      }
    },
    "additionalProperties": false
  }
}

A few deliberate choices:

  • Two equal inputs, chosen by what the model has been given. The description does not rank them. It tells the model to use template_id only when it has been given an ID, so it never guesses one, and otherwise to write HTML. The trade-offs are below.
  • The schema stays flat. "Exactly one of template_id or html" could be written with oneOf, but support for schema combinators varies between function-calling APIs, especially at the top level. The rule is stated in the description and enforced by the executor instead, which returns a clear error if the model sends both.
  • No API key, base URL or output path in the schema. Anything in the schema is chosen by the model. Credentials and destinations belong to your server.
  • The model formats values. Templates lay out values; they do not calculate. The description tells the model to send totals and dates already formatted, which is how the sample invoice data is shaped.

HTML or a template ID: the trade-offs

html, with optional datatemplate_id with data
SetupAn API key. Nothing to save first.Save a template in the app, then give the agent its ID and field names (in the system prompt, for example).
Who decides the layoutWhoever writes the HTML: the model on each call, or your codeThe saved template, reviewed once and edited in the app without a deploy
Range of documentsAnything the model or your code can express in HTML and CSSThe documents you have templates for
Consistency between callsVaries with the markup; check output for documents that must look the same every timeSame layout every call; only the values change
What the model writes per callThe whole document, so more output tokens and a larger argument (capped at 200,000 characters in the example)Only the values (capped at 512 KB of JSON in the example)

There is a middle route if you want a fixed layout without saving a template: keep the HTML in your own code, let the tool accept only data, and have the executor send both to POST /html-to-pdf. The executor in this guide does not do that, but the change is a few lines in the request body.

Registering it with your model API

Most function-calling APIs take the same three things, a name, a description and a JSON Schema for the arguments, under slightly different field names. Wrap the object above to match your provider's request format:

Provider APIWhere the schema goesHow the result goes backError flag
Anthropic Messages APItools[] entry with name, description, input_schemaa tool_result block with tool_use_id, in the next user messageis_error: true
OpenAI Responses APItools[] entry with type: "function", name, description, parametersa function_call_output item with call_id and outputnone documented; put the error JSON in output

Field names are from each provider's documentation as accessed on 23 November 2026 (see sources). For other providers and frameworks, look for the same three pieces: name, description and a JSON Schema for the arguments, plus a way to send a result back against the call's ID. Strict or structured modes add their own schema rules. OpenAI's strict-mode example, for instance, lists every property in required and sets additionalProperties: false, so check your provider's page before switching such a mode on.

Step 2: Write the executor

The executor is the only code that talks to SublimePDF. It runs on your server, reads the key from the environment, and always returns a JSON result instead of throwing. This is the request part of executeGeneratePdf in the TypeScript example:

const { template_id, data, html, filename } = checked.args;
const source = template_id !== undefined ? "template" : "html";
const url = source === "template"
    ? `${config.baseUrl}/templates/${encodeURIComponent(template_id as string)}/generate`
    : `${config.baseUrl}/html-to-pdf`;
const body = source === "template" ? { data } : { html, ...(data ? { data } : {}) };
const idempotencyKey = randomUUID(); // one key per tool call, reused for every retry of that call
 
const res = await fetch(url, {
    method: "POST",
    headers: {
        Authorization: `Bearer ${config.apiKey}`,
        "Content-Type": "application/json",
        Accept: "application/pdf",
        "Idempotency-Key": idempotencyKey,
    },
    body: JSON.stringify(body),
    signal: AbortSignal.timeout(config.requestTimeoutMs),
});

Before that request, validateArgs checks the model's arguments against the same rules as the schema: no unknown keys, exactly one of template_id or html, data present with a template, a size cap on data and html, and a file name that cannot contain directories. Validate even if your provider has a strict schema mode. Model output is untrusted input, and the filename check is what stops a value like ../../etc/passwd from becoming a write outside your output folder.

On success the executor writes the PDF and returns a document reference:

{
  "ok": true,
  "document": {
    "document_id": "f059800f-9887-467a-9d9a-298536b8ae2f",
    "source": "template",
    "template_id": "invoice",
    "file_name": "invoice-f059800f.pdf",
    "path": "/srv/app/generated-pdfs/invoice-f059800f.pdf",
    "uri": "file:///srv/app/generated-pdfs/invoice-f059800f.pdf",
    "bytes": 63998,
    "pages": 1,
    "sha256": "f3f1a694216c994de1a3eb24e8b6c434595eeeb1eb4469762de413d2cc1ed99c",
    "content_type": "application/pdf"
  }
}

That output came from the local mock, which answers with the sample invoice PDF whatever data you send. The size and hash are those of the sample file, and the path was shortened for this page.

Why a reference and not the PDF

Do not return the PDF to the model, not even as base64. A one-page invoice is tens of kilobytes. As base64 that becomes tens of thousands of characters of context that the model cannot use, and it can be cut off or garbled when the model repeats it. The model only needs to know that the document exists and how to refer to it. Your application turns the document_id into whatever the user needs: a download link, an email attachment, a row in a database. In production, replace path and uri with your own storage key or a signed URL.

Step 3: Return errors as tool results

When a call fails, the executor returns { "ok": false, "error": {...} } and your loop sends it back as an ordinary tool result. Do not raise an exception that ends the conversation. The model can then correct a field, ask the user for a missing value, or stop retrying. Every error carries retryable and a plain-language instruction written for the model:

HTTP statusExecutor behaviourWhat the tool result tells the model
400, 422Returns the error immediatelyFix the named field (or ask the user) and call once more; never resend the same arguments
401, 403Returns immediatelyPDF generation is not configured; do not retry
402Returns immediatelyThe monthly document allowance is used up; do not retry, tell the user
404Returns immediatelyThe template ID does not exist; ask the user, do not guess
409Waits for Retry-After and retries with the same Idempotency-Key, up to five timesThe same document is still being generated; tell the user it is in progress
413Returns immediatelySend fewer rows or shorter text
429Waits for Retry-After once (up to 10 s), then retriesIf still limited, stop and tell the user to try shortly
500, 502, 503, networkRetries twice with backoff and the same Idempotency-KeyIf still failing, stop and say the document could not be generated

This is what the model received when the test omitted a required field from the report data:

{
  "ok": false,
  "error": {
    "status": 422,
    "type": "validation_error",
    "message": "data.summary is required",
    "field": "summary",
    "retryable": false,
    "instruction": "The data is invalid at \"summary\". Correct that value (or ask the user for it) and call the tool again once. Do not resend the same arguments."
  }
}

That output came from the local mock. The API itself names the field with its full path ("field": "data.summary") and adds a request_id to every error. The executor reads type, message and field from the API's JSON error body, { "error": { "type", "message", "field", "code", "request_id" } }, and falls back to the HTTP status line when the body is not JSON, for example an HTML page from a proxy. The error handling guide covers retry policy in more depth.

One Idempotency-Key per tool call

The executor creates one Idempotency-Key per tool call and reuses it for every retry of that call. If a 503 or a dropped connection hides whether the first attempt succeeded, the retry carries the same key. If the first render finished, SublimePDF returns the stored PDF with Idempotent-Replayed: true and does not count it again; if it is still running, the API answers 409 with Retry-After and the executor waits for it rather than rendering twice. Reusing a key with different arguments is rejected with 422. When the model makes a new tool call, for example after correcting a field, that is a new key: it is a different request. The test suite checks this. A 503 followed by a success produced two requests with the same key.

Step 4: Connect it to the agent loop

The loop is the same in every framework: send the conversation with the tool definitions, run each tool call the reply contains, send the results back against each call's ID, and stop when the model answers in text. This complete example does that with the Anthropic Messages API and its TypeScript SDK. It is agent-loop-claude.ts without its header comment, and it sits next to generate-pdf-tool.ts:

import Anthropic from "@anthropic-ai/sdk";
import { executeGeneratePdf, generatePdfTool } from "./generate-pdf-tool.ts";
 
const client = new Anthropic(); // reads ANTHROPIC_API_KEY from the environment
 
const tools: Anthropic.Tool[] = [
    {
        name: generatePdfTool.name,
        description: generatePdfTool.description,
        input_schema: generatePdfTool.parameters as unknown as Anthropic.Tool.InputSchema,
    },
];
 
// Optional: tell the model which saved templates it may use. Without this line it sends html.
const system = process.env.SUBLIMEPDF_TEMPLATE_HINT; // e.g. "Saved template: report (fields: title, summary, ...)"
 
const prompt =
    process.argv[2] ??
    "Create a one-page packing slip PDF for order 1042 to Example Co, 1 Sample Road, Leeds: 2 x A5 notebook, 1 x pen set.";
const messages: Anthropic.MessageParam[] = [{ role: "user", content: prompt }];
 
const MAX_TURNS = 8; // stops a model that keeps retrying from looping forever
 
for (let turn = 0; turn < MAX_TURNS; turn++) {
    const response = await client.messages.create({
        model: "claude-opus-5-5",
        max_tokens: 16000,
        ...(system ? { system } : {}),
        tools,
        messages,
    });
    messages.push({ role: "assistant", content: response.content });
 
    if (response.stop_reason !== "tool_use") {
        for (const block of response.content) {
            if (block.type === "text") console.log(block.text);
        }
        if (response.stop_reason !== "end_turn") console.error(`stopped: ${response.stop_reason}`);
        break;
    }
 
    // One tool_result per tool_use block, all in a single user message.
    const results: Anthropic.ToolResultBlockParam[] = [];
    for (const block of response.content) {
        if (block.type !== "tool_use") continue;
        const result =
            block.name === generatePdfTool.name
                ? await executeGeneratePdf(block.input)
                : { ok: false, error: { type: "unknown_tool", message: `No tool named ${block.name}` } };
        console.error(`[${block.name}]`, JSON.stringify(result));
        results.push({ type: "tool_result", tool_use_id: block.id, content: JSON.stringify(result), is_error: !result.ok });
    }
    messages.push({ role: "user", content: results });
}

Run it with both keys in the environment. The SublimePDF key is read only by the executor; the model provider's key only by the SDK client:

npm install @anthropic-ai/sdk
export ANTHROPIC_API_KEY=YOUR_ANTHROPIC_KEY
export SUBLIMEPDF_API_KEY=YOUR_API_KEY
node agent-loop-claude.ts "Create a packing slip PDF for order 1042"

The file type-checks under --strict against @anthropic-ai/sdk 1.12.0. We ran it against a local stand-in for the Messages endpoint and the SublimePDF mock, which confirmed the tool call, the saved PDF and the tool_result sent back; we did not run it against a live model from this repository.

For another provider, keep everything except the three provider-specific parts from the table above: how the tool is declared, how tool calls are read from the reply, and how results are sent back. With the OpenAI Responses API, for example, tool calls arrive as function_call items whose arguments is a JSON string, so parse it before calling executeGeneratePdf. validateArgs rejects anything that is not an object.

For documents that go to a customer, such as invoices, consider a confirmation step: let the agent generate the PDF, show it to a person, and send it only after approval.

Step 5: Test without an API key

The mock server implements the documented routes, auth check and error statuses locally. It answers template calls with the sample PDFs, and /html-to-pdf with a fixed placeholder page (it does not render your HTML). Template IDs rate-limited and flaky trigger a 429 and a single 503. Outside this repository it needs the two sample PDFs in a samples folder, which the commands below download:

mkdir sublimepdf-agent && cd sublimepdf-agent
BASE=https://sublimepdf.com/samples
for f in generate-pdf-tool.ts generate_pdf_tool.py mock-server.mjs package.json; do
  curl -fsSO "$BASE/fixtures/agent-quickstart/$f"
done
mkdir -p samples/report samples/invoice
curl -fsS -o samples/report/report.pdf "$BASE/report/report.pdf"
curl -fsS -o samples/invoice/invoice.pdf "$BASE/invoice/invoice.pdf"
curl -fsS -o report-data.json "$BASE/report/data.json"
 
SAMPLES_DIR=./samples node mock-server.mjs &
export SUBLIMEPDF_API_BASE_URL=http://127.0.0.1:4010/v1
export SUBLIMEPDF_API_KEY=test_key_not_real
 
node generate-pdf-tool.ts --schema
node generate-pdf-tool.ts '{"html":"<!doctype html><h1>Packing slip 1042</h1>"}'
node generate-pdf-tool.ts "$(jq -c '{template_id: "report", data: .}' report-data.json)"
python3 generate_pdf_tool.py '{"template_id":"report","data":{"title":"Week 47"}}'  # a 422 tool result

The repository's test script runs both executors through 11 scenarios each: HTML mode, success with each template, a 503 then success, 422, 404, 429, both modes sent at once, missing data, a path-traversal file name, an extra argument and a missing key. All 22 runs passed on Node.js 24.5 and Python 3.9.6 (last run 23 November 2026), and the TypeScript file type-checks under --strict. The results file lists every tool result. These tests exercise the client path against a mock. They do not replace a test against your own account.

To switch to production, unset SUBLIMEPDF_API_BASE_URL (the default is https://api.sublimepdf.com/v1) and set your real key. HTML calls then work as they are; for template calls, use a template ID from your workspace.

Production checklist

  • The key lives only in the executor's environment and never in prompts, logs or tool results. The mock logs whether a bearer token was present, never its value.
  • Arguments are validated on your side, even with a provider's strict mode.
  • data and html have size caps. The example uses 512 KB and 200,000 characters; tune them to your templates.
  • Tool results carry a reference, never PDF bytes.
  • Each tool call has its own Idempotency-Key, reused only for retries of that call.
  • Rate limits are respected: the executor honours Retry-After once and then hands control back to the model. Plan limits are on the pricing page.
  • Documents that leave your system pass through a person or a rule you trust.

When to use MCP instead

If your agent runs inside an MCP host, such as a desktop assistant or IDE that discovers tools over the Model Context Protocol, you can expose this same executor as an MCP tool. The MCP integration page shows a small self-run MCP server that wraps executeGeneratePdf and was tested with the official MCP client. MCP is optional. Plain tool calling, as above, is the shorter path when you control the agent loop.

For the full endpoint list, options and status codes, see the API reference. For a worked example of an agent that writes weekly reports, see AI agent reports. The API authentication guide covers storing and rotating the key the executor uses, and the webhooks guide covers asynchronous renders.

Sources

  1. JSON Schema Draft 2020-12 · accessed 23 November 2026
  2. Claude API docs: Define tools · accessed 23 November 2026
  3. Claude API docs: Handle tool calls · accessed 23 November 2026
  4. OpenAI API docs: Function calling · accessed 23 November 2026

Generate your first PDF with one API call.

Create an account, copy an API key and send HTML, or a template ID with JSON data, from your code or your agent.