/** * Framework-neutral "generate_pdf" tool for LLM agents. * * - `generatePdfTool` is the tool definition (name, description, JSON Schema) * you register with whatever function-calling API or agent framework you use. * - `executeGeneratePdf(args)` is the executor your code runs when the model * calls the tool. It validates the arguments, calls SublimePDF with the API * key from the environment (the key never enters the model context), saves * the PDF and returns a small document reference. Failures come back as * structured tool results the model can act on, not exceptions. * * template mode: { template_id, data } -> POST {base}/templates/{id}/generate body { data } * html mode: { html, data? } -> POST {base}/html-to-pdf body { html, data? } * * Runs on Node.js 22.18+ / 23.6+ directly (type stripping) or via `npx tsx`. * No dependencies. * * SUBLIMEPDF_API_KEY=... node generate-pdf-tool.ts '{"template_id":"report","data":{...}}' * node generate-pdf-tool.ts --schema * * Environment: * SUBLIMEPDF_API_KEY required; read only by the executor * SUBLIMEPDF_API_BASE_URL default https://api.sublimepdf.com/v1 * PDF_OUTPUT_DIR default ./generated-pdfs */ import { createHash, randomUUID } from "node:crypto"; import { mkdir, writeFile } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; export const generatePdfTool = { 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, }, } as const; export interface GeneratePdfArgs { template_id?: string; data?: Record; html?: string; filename?: string; } export interface DocumentReference { document_id: string; source: "template" | "html"; template_id: string | null; file_name: string; path: string; uri: string; bytes: number; pages: number | null; sha256: string; content_type: "application/pdf"; } export interface ToolError { status: number | null; type: string; message: string; field?: string; retryable: boolean; instruction: string; } export type ToolResult = { ok: true; document: DocumentReference } | { ok: false; error: ToolError }; export interface ExecutorConfig { apiKey: string | undefined; baseUrl: string; outputDir: string; maxDataBytes: number; maxHtmlChars: number; maxRetryAfterSeconds: number; serverErrorRetries: number; requestTimeoutMs: number; } export function configFromEnv(): ExecutorConfig { return { apiKey: process.env.SUBLIMEPDF_API_KEY, baseUrl: (process.env.SUBLIMEPDF_API_BASE_URL ?? "https://api.sublimepdf.com/v1").replace(/\/$/, ""), outputDir: process.env.PDF_OUTPUT_DIR ?? "generated-pdfs", maxDataBytes: 512 * 1024, maxHtmlChars: 200_000, maxRetryAfterSeconds: 10, serverErrorRetries: 2, requestTimeoutMs: 60_000, }; } const ALLOWED_KEYS = ["template_id", "data", "html", "filename"]; const ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/; const FILENAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,95}$/; /** Validate untrusted model output against the schema above. Returns problems, not exceptions. */ export function validateArgs( raw: unknown, limits: { maxDataBytes: number; maxHtmlChars: number } = { maxDataBytes: 512 * 1024, maxHtmlChars: 200_000 }, ): { ok: true; args: GeneratePdfArgs } | { ok: false; problems: string[] } { if (typeof raw !== "object" || raw === null || Array.isArray(raw)) { return { ok: false, problems: ["arguments must be a JSON object"] }; } const input = raw as Record; const problems: string[] = []; for (const key of Object.keys(input)) { if (!ALLOWED_KEYS.includes(key)) problems.push(`unknown argument "${key}"`); } const hasTemplate = input.template_id !== undefined; const hasHtml = input.html !== undefined; if (hasTemplate === hasHtml) { problems.push("provide exactly one of template_id or html"); } if (hasTemplate && (typeof input.template_id !== "string" || !ID_PATTERN.test(input.template_id))) { problems.push("template_id must be 1-64 characters: letters, digits, '_' or '-'"); } if (hasHtml && (typeof input.html !== "string" || input.html.trim() === "")) { problems.push("html must be a non-empty string"); } else if (hasHtml && (input.html as string).length > limits.maxHtmlChars) { problems.push(`html must be at most ${limits.maxHtmlChars} characters (limit set by this executor)`); } const data = input.data; if (data === undefined) { if (hasTemplate) problems.push("data is required with template_id"); } else if (typeof data !== "object" || data === null || Array.isArray(data)) { problems.push("data must be a JSON object"); } else if (Buffer.byteLength(JSON.stringify(data)) > limits.maxDataBytes) { problems.push(`data must be smaller than ${limits.maxDataBytes} bytes when serialised`); } if (input.filename !== undefined && (typeof input.filename !== "string" || !FILENAME_PATTERN.test(input.filename))) { problems.push("filename must be a plain file name (letters, digits, '.', '_' or '-'; no directories)"); } if (problems.length > 0) return { ok: false, problems }; return { ok: true, args: input as GeneratePdfArgs }; } const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); /** Best-effort page count for PDFs that keep page objects uncompressed (true for Chromium output). Use a PDF library in production. */ function countPages(pdf: Buffer): number | null { const matches = pdf.toString("latin1").match(/\/Type\s*\/Page(?![s\w])/g); return matches ? matches.length : null; } function instructionFor(status: number | null, field?: string): { retryable: boolean; instruction: string } { switch (status) { case 400: case 422: return { retryable: false, instruction: field ? `The data is invalid at "${field}". Correct that value (or ask the user for it) and call the tool again once. Do not resend the same arguments.` : "The request was rejected. Correct the arguments described in the message and call the tool again once. Do not resend the same arguments.", }; case 401: case 403: return { retryable: false, instruction: "The PDF service is not authorised on this server. Do not retry; tell the user PDF generation is not configured." }; case 402: return { retryable: false, instruction: "The account's monthly document allowance is used up. Do not retry; tell the user to upgrade the plan or wait for the monthly reset." }; case 404: return { retryable: false, instruction: "That template ID does not exist. Do not guess IDs; ask the user which template to use." }; case 409: return { retryable: true, instruction: "The same document is still being generated. Do not call this tool again in this turn; tell the user it is still in progress." }; case 413: return { retryable: false, instruction: "The request is too large. Send fewer rows or shorter text, or ask the user to split the document." }; case 429: return { retryable: true, instruction: "Rate limited even after waiting. Do not call this tool again in this turn; tell the user to try again shortly." }; default: return { retryable: true, instruction: "The PDF service failed after retries. Do not call this tool again in this turn; tell the user the document could not be generated." }; } } async function errorFromResponse(res: Response): Promise { let type = "http_error"; let message = `HTTP ${res.status}`; let field: string | undefined; try { // Error body: { "error": { "type", "message", "field"?, "code"?, "request_id" } }. Falls back to the status line. const body = (await res.json()) as { error?: { type?: string; message?: string; field?: string } }; type = body.error?.type ?? type; message = body.error?.message ?? message; field = body.error?.field; } catch { /* non-JSON error body */ } return { status: res.status, type, message, ...(field ? { field } : {}), ...instructionFor(res.status, field) }; } export async function executeGeneratePdf(rawArgs: unknown, config: ExecutorConfig = configFromEnv()): Promise { const checked = validateArgs(rawArgs, config); if (!checked.ok) { return { ok: false, error: { status: null, type: "invalid_arguments", message: checked.problems.join("; "), retryable: false, instruction: "Fix the arguments to match the tool schema and call the tool again once.", }, }; } if (!config.apiKey) { return { ok: false, error: { status: null, type: "configuration_error", message: "SUBLIMEPDF_API_KEY is not set on the server.", ...instructionFor(401) } }; } const { template_id, data, html, filename } = checked.args; const source: "template" | "html" = 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 let serverErrorsLeft = config.serverErrorRetries; let waitedForRateLimit = false; let inFlightWaitsLeft = 5; // 409 idempotency_in_flight: an earlier attempt with this key is still rendering for (let attempt = 1; ; attempt++) { let res: Response; try { 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), }); } catch (err) { if (serverErrorsLeft-- > 0) { await sleep(500 * 2 ** (attempt - 1)); continue; } return { ok: false, error: { status: null, type: "network_error", message: String(err), ...instructionFor(null) } }; } if (res.ok && (res.headers.get("content-type") ?? "").includes("application/pdf")) { const pdf = Buffer.from(await res.arrayBuffer()); const documentId = idempotencyKey; const fileName = filename ? (filename.endsWith(".pdf") ? filename : `${filename}.pdf`) : `${template_id ?? "document"}-${documentId.slice(0, 8)}.pdf`; await mkdir(config.outputDir, { recursive: true }); const file = path.resolve(config.outputDir, fileName); await writeFile(file, pdf); return { ok: true, document: { document_id: documentId, source, template_id: template_id ?? null, file_name: fileName, path: file, uri: pathToFileURL(file).href, bytes: pdf.length, pages: countPages(pdf), sha256: createHash("sha256").update(pdf).digest("hex"), content_type: "application/pdf", }, }; } if (res.status === 429 && !waitedForRateLimit) { const retryAfter = Number(res.headers.get("retry-after") ?? "1"); if (Number.isFinite(retryAfter) && retryAfter <= config.maxRetryAfterSeconds) { waitedForRateLimit = true; await sleep(Math.max(retryAfter, 0) * 1000); continue; } } if (res.status === 409 && inFlightWaitsLeft-- > 0) { // A timed-out earlier attempt with the same Idempotency-Key is still running; wait, then // retry with the same key to receive its result instead of rendering twice. const retryAfter = Number(res.headers.get("retry-after") ?? "2"); await sleep(Math.min(Math.max(Number.isFinite(retryAfter) ? retryAfter : 2, 1), config.maxRetryAfterSeconds) * 1000); continue; } if ((res.status === 500 || res.status === 502 || res.status === 503) && serverErrorsLeft-- > 0) { await sleep(500 * 2 ** (attempt - 1)); continue; } if (res.ok) { return { ok: false, error: { status: res.status, type: "unexpected_response", message: `Expected application/pdf, got ${res.headers.get("content-type")}`, ...instructionFor(null) } }; } return { ok: false, error: await errorFromResponse(res) }; } } // CLI: print the schema, or run one tool call and print the tool result JSON. if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { const arg = process.argv[2]; if (arg === "--schema") { console.log(JSON.stringify(generatePdfTool, null, 2)); } else { let parsed: unknown; try { parsed = JSON.parse(arg ?? ""); } catch { parsed = arg; } const result = await executeGeneratePdf(parsed); console.log(JSON.stringify(result, null, 2)); process.exitCode = result.ok ? 0 : 1; } }