Draft EPUB figure alt text with CometAPI using the image and the task it supports. Review the proposed sentence against the artwork and chapter, then put the approved wording in an explicit {alt="..."} attribute in Pandoc Markdown. Keep the visible caption in square brackets. Open the exported EPUB and check that the chapter contains both the approved description and the caption. Pandoc User’s Guide

Last reviewed: 2026-11-23 (Asia/Shanghai).

Choose what the reader needs from the figure

Start with an informative image in a Markdown manuscript. In a workshop guide, a figure shows how to position a bracket before marking two screw positions. A caption such as “Figure 1. Bracket orientation before marking.” gives the chapter a label to refer to. The alternative text should explain where the holes are. “A picture of a bracket” identifies the object and leaves the reader guessing where to mark.

Assign each image a purpose before sending it for a draft. For a simple informative figure, write a brief description that conveys the information the reader will use. Give a purely decorative image an empty alt attribute. Look at the surrounding text when deciding that an image is redundant. For a wiring diagram or chart whose relationships matter, supply an extended description or a table in the chapter and check it against the source diagram or data. If the image is the only content in a link, write a text alternative that conveys the link’s purpose. The caption pattern below is for a standalone informative figure. W3C WAI alt decision tree · DAISY image descriptions

Cover the bracket drawing and read the instruction together with the proposed description. The chapter can tell the reader to put the upright on the left. The alt text can then locate one hole near the top of the upright and the other near the end of the horizontal arm. Repeat that check if the illustration is replaced or cropped. The same sentence can become inaccurate even when the caption still fits.

Request one description for an approved image

Use Node.js 24 and an image your team has cleared for sharing with the provider. The live example accepts a publicly reachable HTTPS URL you control, with no query parameters. Use a PNG or JPEG that your chosen model accepts and verify that it shows the same artwork as the local manuscript image. Give the model one short description of the reader’s task. The request needs only the image location and that task.

Set COMETAPI_KEY through your runtime secret mechanism. Set COMETAPI_MODEL to a model in your account that supports images on Chat Completions and accepts max_completion_tokens. The route takes a text part and an image_url part in one message. Check the model and route together before running the example. CometAPI Chat Completions reference · CometAPI model catalog validation

Save the request and acceptance checks as draft-alt.mjs.

export async function suggestAlt(image, task, { key, model }, send = fetch) {
  const imageUrl = new URL(image);
  if (imageUrl.protocol !== 'https:' || imageUrl.username || imageUrl.password ||
      imageUrl.search || imageUrl.hash) throw new Error('use_public_https_image');
  if (!key?.trim() || !model?.trim() || !task?.trim() || task.length > 400) {
    throw new Error('check_configuration_and_task');
  }

  const response = await send('https://api.cometapi.com/v1/chat/completions', {
    method: 'POST',
    redirect: 'error',
    signal: AbortSignal.timeout(30_000),
    headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },
    body: JSON.stringify({
      model, stream: false, max_completion_tokens: 4096,
      messages: [{ role: 'user', content: [
        { type: 'text', text: 'Draft one line of plain alt text of at most 200 characters. ' +
          'Use only details visible in the image that help with this reader task: ' + task +
          '. Do not infer dimensions or materials. Return only the proposed description.' },
        { type: 'image_url', image_url: { url: imageUrl.href } },
      ] }],
    }),
  });
  const media = response.headers.get('content-type')?.split(';')[0].trim().toLowerCase();
  if (response.status !== 200 || media !== 'application/json' || !response.body) {
    await response.body?.cancel().catch(() => {});
    throw new Error(response.status === 200 ? 'expected_json' : `http_${response.status}`);
  }

  const chunks = [];
  let size = 0;
  for await (const chunk of response.body) {
    size += chunk.byteLength;
    if (size > 65_536) throw new Error('reply_too_large');
    chunks.push(chunk);
  }
  const json = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks)));
  const choice = json?.choices?.[0];
  const message = choice?.message;
  const noTools = message?.tool_calls == null ||
    (Array.isArray(message.tool_calls) && message.tool_calls.length === 0);
  const alt = typeof message?.content === 'string' ? message.content.trim() : '';
  if (json?.object !== 'chat.completion' || !Array.isArray(json.choices) ||
      json.choices.length !== 1 || choice?.finish_reason !== 'stop' ||
      message?.role !== 'assistant' || message.refusal != null || !noTools ||
      message.function_call != null || !alt || alt.length > 200 ||
      !alt.isWellFormed() || /[\p{Cc}\p{Zl}\p{Zp}]/u.test(alt)) {
    throw new Error('draft_not_accepted');
  }
  return alt;
}

Save the entry point as run-alt.mjs.

import { suggestAlt } from './draft-alt.mjs';

try {
  const [image, task] = process.argv.slice(2);
  const draft = await suggestAlt(image, task, {
    key: process.env.COMETAPI_KEY, model: process.env.COMETAPI_MODEL,
  });
  process.stdout.write(draft + '\n');
} catch {
  console.error('No draft. Check image, model, and request outcome before trying again.');
  process.exitCode = 1;
}

Set APPROVED_IMAGE_URL to the location of the cleared asset and run one request. Keep draft output in your editorial workspace.

node run-alt.mjs "$APPROVED_IMAGE_URL" 'Orient the bracket before marking both screw holes.'

A successful run prints one candidate line. The sample uses a 30-second timeout and rejects a response body larger than 64 KiB. The local limit of 200 JavaScript string code units keeps the draft short enough to review quickly. An editor can choose longer wording when the reader’s task requires it. A refusal or a length finish outcome stops the draft. CometAPI counts reasoning tokens toward max_completion_tokens for the documented GPT-6 Astra example, so short visible text can still use a larger generation budget. CometAPI Chat Completions reference

If the command fails before printing a draft, check the image from an unauthenticated connection and confirm that the account can use the selected model with images on this route. After a transport timeout, check the original attempt before submitting again. You can continue with a human-written description while you investigate. If your project already uses Responses, check its image request and output fields in the companion guide. Visual Q&A client walkthrough

Put the reviewed description in the Markdown attribute

Copy the sentence after someone checks the artwork, its orientation, and the language of the chapter. A completion can pass every response check and still swap left and right, miss a hole, or invent what the bracket is made of. The export fixture uses hand-written wording. To try it offline, save this local test graphic as assets/bracket.svg beside the manuscript.

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 160 100" width="160" height="100">
  <rect width="160" height="100" fill="white"/>
  <path d="M25 20h35v43h75v23H25z" fill="#334155"/>
  <circle cx="43" cy="39" r="6" fill="white"/>
  <circle cx="105" cy="74" r="6" fill="white"/>
</svg>

Save workshop.md with the image in its own paragraph. Pandoc’s implicit_figures extension turns a standalone image with nonempty bracket text into a figure with that text as its caption. With link_attributes enabled, the explicit alt attribute supplies the image description. A quoted image title in parentheses sets a separate field. Pandoc User’s Guide

---
title: Workshop guide
lang: en
---

# Fit the bracket

Set the upright on the left with the horizontal arm extending to the right. Mark both screw positions.

![Figure 1. Bracket orientation before marking.](assets/bracket.svg){alt="An L-shaped bracket has one screw hole near the top of the upright and one near the end of the horizontal arm."}

Type the reviewed wording into the attribute as plain text. For a literal double quote or ampersand inside the double-quoted attribute, use &quot; or &amp; and inspect the output. Use the local asset path in the manuscript so the book packages its own copy. If the image is inline in a sentence, check its output independently because the standalone figure rule requires its own paragraph.

Inspect the chapter inside the EPUB

Run these commands from the directory that holds workshop.md and assets, with Pandoc and unzip installed. Use a working copy of the book and inspect the archive listing for the actual chapter path.

pandoc --from=markdown+implicit_figures+link_attributes --to=epub3 workshop.md -o workshop.epub
unzip -l workshop.epub
unzip -p workshop.epub EPUB/text/ch001.xhtml

With Pandoc 3.14, the fixture stores the chapter at EPUB/text/ch001.xhtml and the graphic at EPUB/media/file0.svg. The chapter contains these elements.

<figure>
<img src="../media/file0.svg" alt="An L-shaped bracket has one screw hole near the top of the upright and one near the end of the horizontal arm." />
<figcaption>Figure 1. Bracket orientation before marking.</figcaption>
</figure>

Compare the alt attribute with the approved description. Check that the caption still contains the intended figure number and wording. Resolve src relative to the chapter path and find the asset in the archive. For a failure check, remove the explicit attribute in a copy of the manuscript and rebuild to a fresh filename. Pandoc 3.14 put the caption text in alt and marked the figcaption with aria-hidden="true" in that build. Restore the explicit attribute and repeat the chapter check before sharing the book.

The draft helper was exercised on Node.js 24.22.1 with synthetic responses, including a completed text reply and rejected replies for truncation, refusal, multiple lines, and oversized content. Pandoc 3.14 produced the distinct text fields and the missing-attribute comparison locally. Live model behavior and reading-system behavior remain to be checked. Open the actual book with the reading systems and assistive technology your readers use. Confirm that readers can find the figure, hear the intended description, and follow the instruction in context. Repeat that check after changes to book templates or the converter. DAISY image descriptions

Once you have verified the local markup, pick one approved image and Start with CometAPI . Compare the draft with a colleague’s description of what the reader needs to do. Save the reviewed wording in the manuscript so later builds can use it without another API call.

Sources checked

  • The provider documents the multimodal message parts, authentication, finish outcomes, and completion budget. CometAPI Chat Completions
  • The converter manual covers image markup, the explicit alt override for implicit figures, and EPUB output. Pandoc User’s Guide
  • The web accessibility guidance distinguishes informative, decorative, functional, and complex images by their purpose in context. W3C WAI alt decision tree
  • The accessible publishing guide explains short alternatives and extended descriptions in book content. DAISY image descriptions