Features

Polotno AI

Generate images and run Expand, Generative fill and Upscale in the Polotno editor, paid from your prepaid Polotno balance

Polotno AI is Polotno's paid AI API, built into the editor. Polotno runs the models, so your app needs no AI provider of its own.

What it adds

The AI tab. The side panel gets an AI tab, where the user writes a prompt, picks an Aspect ratio and clicks Generate to make one image. The ratio list starts with Page, the default, which picks the ratio closest to the page's shape. The other entries are the ratios the model supports. A Model picker appears when your app offers more than one model. A Reference image field appears when the model takes one, with Use selected for the selected image and Upload for a file. A click on a result adds it to the page, and a drag drops it into an image or a frame.

The canvas tools. The AI edit menu in the image toolbar works on the selected image:

  • Expand: the user drags the frame past the image edges, and the model fills the new area. The prompt is optional.
  • Generative fill: the user drags a selection on the image, then picks Replace to fill it from a prompt, or Remove to erase what is there.
  • Upscale: one click raises the image's resolution.

Remove background, in the same menu, is a separate feature with its own billing. See Remove Image Background.

Turn it on

Your server keeps a server key and trades it for short-lived tokens. The editor sends a token with each paid call, so the key never reaches the browser. The HTTP side of both is in Server keys and tokens.

Create a server key

A server key is an API key whose only domain is server. The browser key you pass to createStore can't pay for AI.

In My account, open the API & Usage tab, click Create new API key, choose Server / Private and click Create server key. On an account with no key yet, the tab shows that button after you create a browser key for your domain. Your editor needs that key too.

Keep the server key on your server, for example in an environment variable named POLOTNO_SERVER_KEY. Anyone who has it can spend your balance.

Add a token endpoint

Add a route to your server that mints a token with POST https://api.polotno.com/api/tokens, sending the server key as Authorization: Bearer <key>. The route forwards the API's response unchanged, status and body, so the editor sees refusals too. Put the route behind your login: anyone who can call it spends your balance.

The request body is optional JSON with two fields. Server keys and tokens lists their limits.

  • user: your own id for the signed-in user, as a string. Polotno records it with each charge. Never send an email: the API refuses a value with @.
  • expires_in: the token's lifetime in seconds. The default is 900.

The answer uses OAuth 2.0 field names: { "access_token": "pt_…", "token_type": "Bearer", "expires_in": 900, "expires_at": "…" }. Minting a token costs nothing.

app.post('/api/polotno-token', async (req, res) => {
  // req.user comes from your own login middleware.
  if (!req.user) {
    return res.status(401).json({ error: { code: 'unauthorized' } });
  }
  const response = await fetch('https://api.polotno.com/api/tokens', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.POLOTNO_SERVER_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ user: String(req.user.id) }),
  });
  // Forward the API's response unchanged, so the editor sees refusals too.
  res.status(response.status).type('json').send(await response.text());
});

Give the editor tokens

Call setTokenFunc once, at startup, with a function that asks your endpoint:

import { setTokenFunc } from 'polotno/config';

setTokenFunc(async () => {
  const response = await fetch('/api/polotno-token', { method: 'POST' });
  return response.json();
});

The editor calls the function when a paid call needs a token, one request at a time, and keeps each token until 30 seconds before it expires. After a token_expired or invalid_token refusal, it gets one new token and retries the call once. A function that doesn't answer within 15 seconds fails the call.

The function can also return a server key as it is. Anyone who opens the page can then copy the key and spend your balance, and the editor warns about it in the console. If a prototype has to work this way, give it a separate server key and remove that key when you're done.

List the tools

import { setAiTools } from 'polotno/config';

setAiTools([
  'ai.image.generate', // the AI tab
  'ai.image.expand',
  'ai.image.replace-object',
  'ai.image.remove-object',
  'ai.image.upscale',
]);

ai.image.replace-object and ai.image.remove-object are Generative fill's Replace and Remove; with both listed, the user switches between them.

No Polotno AI tool shows by default. The AI tab and each canvas tool appear once setAiTools lists them, so a tool that a later SDK version adds stays hidden until you add it.

Each call replaces the whole list. If you pass your own sections to SidePanel, add AiSection from polotno/side-panel to them, or the AI tab has no place to appear.

To put the same panel in a section of your own, render AiImagesPanel from polotno/side-panel/ai-images-panel with the store prop. Your section shows even when setAiTools leaves out ai.image.generate.

Models

setAiModels sets the models a tool offers, in order. The first is the default:

import { setAiModels } from 'polotno/config';

setAiModels('ai.image.generate', ['seedream-lite', 'flux']);
  • The AI tab shows a Model picker when it offers more than one model. It skips an id that the model list doesn't have, with a console warning.
  • The canvas tools show no picker. Each sends the first model you set, for every user. The editor doesn't check this id, so an id the API doesn't know fails the call.
  • With nothing set, a tool runs the API's default model, and the AI tab shows no picker.

The ids come from the public model list, which needs no key:

curl https://api.polotno.com/api/ai/models

It lists each tool by the id that setAiTools takes, and each model by the id that setAiModels takes, with a display name. The AI tab reads this list for its pickers. GET /api/ai/models describes every field.

A model id names a model family and tier, with no version: seedream-lite is Seedream's Lite tier. Once a provider ships a newer version, Polotno can point the id at it, so your users get it with no change to your code. /api/ai/models and the price list always show what runs and what it costs: the model's name, such as Seedream 5 Lite, and its price.

Where results go

The API returns each image as a data: URL, often several MB, or as an https: URL. The editor passes each result it keeps to your upload function, and downloads an https: result first. The design gets the URL your function returns:

import { setUploadFunc } from 'polotno/config';

setUploadFunc(async (file) => {
  const body = new FormData();
  body.append('file', file);
  const response = await fetch('/api/upload', { method: 'POST', body });
  if (!response.ok) throw new Error(`Upload failed: HTTP ${response.status}`);
  const { url } = await response.json();
  return url;
});
  • The same function handles the user's own uploads. See Editor configuration.
  • Each result arrives as a File with a unique name that starts with polotno-ai-, so storage keyed by file name keeps every result.
  • The AI tab uploads a result as it arrives. A canvas tool uploads its result when it applies it, and never uploads a result it drops because the image changed.
  • If the download or the upload fails, the design keeps the URL the API returned, and the console shows one warning with the cause. A data: URL then sits inline in the design JSON.
  • Without setUploadFunc, the default upload function embeds each result as a data: URL and warns about it.

Prices and balance

Every model has its own price per image. The price list is public JSON, the same list Polotno charges by: api.polotno.com/api/pricing. It gives each tool's models with their price in US dollars. Read it from your backend if you show prices to your users or bill them for AI.

The editor shows no prices and no balance. It never requests /api/pricing, and its model list carries no prices, so your users can't find Polotno's prices in their network tab.

The prepaid balance belongs to your Polotno account, and your whole team shares it. Every member sees it on the Balance tab in My account, with the history of top-ups and charges, summed per product per day. Only the account owner adds funds there, charged to the card on file. A top-up is non-refundable and expires 12 months after purchase. The same balance pays for the AI design API.

Polotno emails the account owner when the balance runs low. The next email comes only after another top-up.

When a run is charged

  • Polotno charges a run when the API returns its image, at the chosen model's price. Each run makes one image.
  • Polotno also charges a run when the user cancels it or closes the page after the model has started. The model's provider bills Polotno for that run.
  • Refusals and failures cost nothing: a request the API rejects, a refusal from Errors, a model that fails or runs out of time, and a run cancelled before the model started.

In the editor, only Cancel stops a run. The canvas tools show it while a run is in progress; the AI tab has none. Closing the AI tab, undo, or another change to the image lets the run finish, and Polotno charges it. The AI tab keeps its result for when the user opens it again. A canvas tool drops a result whose image changed while it ran.

Errors

A failed Polotno AI call rejects with a FETCH_FAILED structured error and logs one console warning. A canvas tool's run() rejects with TOOL_FAILED, and its cause is that error. A refusal from the API or from your token endpoint puts its code in details.apiCode. For every refusal, the stock UI shows the same neutral text, error.aiUnavailable in the translations, so your users never see a code or a balance.

apiCodeWhat happenedWhat to do
insufficient_balanceThe balance can't cover the run's price, counting the runs still in progress.The account owner adds funds on the Balance tab in My account.
token_requiredThe call carried no token: setTokenFunc isn't set, or its function returned a browser key. Without a token function, the console warning names setTokenFunc.Give the editor tokens, as in Turn it on.
invalid_tokenThe token is malformed, or the key that minted it can't pay: you removed the key, server isn't its only domain, it isn't linked to exactly one Polotno account, or your endpoint sent something else, such as an unset environment variable. The editor got a new token and retried once before this.Check that your endpoint sends a server key from the API & Usage tab. If it does, contact us with the run id.
token_expiredThe token expired, and so did the new one the editor fetched to retry.Mint a new token for every request to your endpoint. Don't cache tokens on your server.
server_key_requiredYour endpoint called /api/tokens with no key in Authorization: Bearer, or with a token or a value that can't be a key.Send the server key as Authorization: Bearer <key>.
invalid_requestYour endpoint sent a token request that breaks the request rules, such as a user that isn't a string or holds an @.Send user as a string, such as String(user.id).
billing_unavailablePolotno couldn't check the balance, so the run didn't start and costs nothing.Try again.
account_frozenPolotno paused paid calls for this account.Contact us.
no_billing_accountThe server key isn't linked to exactly one Polotno account. A token minted by such a key gets invalid_token instead.Contact us with the run id.

Other failures, such as a network error or a request the API rejects as invalid, also reject with FETCH_FAILED, without an apiCode.

Every answer from a paid endpoint carries an X-Run-Id header. When the API refuses a call, the editor puts it in details.runId and in its console warning. Include it when you contact us about a run.

Use your own AI provider

Register setExpandFunc, setReplaceObjectFunc, setRemoveObjectFunc or setUpscaleFunc to run that canvas tool on your own AI provider instead: your handler wins over Polotno AI and costs nothing from your balance (AI Image Tools).

Local development

Localhost gets no free runs. A paid call from localhost needs a token, and Polotno charges it like any other, so run your token endpoint in development and call setTokenFunc as in production. A separate server key for development lets you remove it without touching production.

FAQ

Can I limit how much each of my users generates?

Yes, in your token endpoint, which decides who gets a token. For a user over your limit, answer with your own refusal, such as { "error": { "code": "limit_reached" } }. The editor treats it like a refusal from the API: it shows the neutral message and puts your code in details.apiCode. The editor keeps a token until 30 seconds before it expires, so a shorter expires_in makes a new limit apply sooner.

How do I stop a leaked key or token from spending my balance?

Click Remove server key on the API & Usage tab in My account, then create a new one for your server. Every token the old key minted stops working at its next paid call, because the API checks the key on each call. A single token can't be revoked, but it expires after 15 minutes, or after the expires_in your endpoint sets.

Where do my images and prompts go?

The editor sends the prompt and the images a tool needs to Polotno's API, which runs the model through Replicate and returns the result. Polotno stores neither images nor prompts, and deletes the files it uploads to Replicate when the run ends. Replicate removes a run's inputs and outputs after an hour. The result then goes to your upload function.

Can I call Polotno AI from my own backend?

Yes. Each tool is an endpoint, POST https://api.polotno.com/api/ai/image/<tool>, where the tool is the last part of its id, such as generate or upscale. Call it with your server key, and Polotno charges the run to the same balance. The AI API page has the HTTP details.

Does Polotno AI work in Electron or a mobile app?

Yes. Polotno AI doesn't check where a call comes from, so a token works in a browser, in Electron and in a mobile WebView. Your app gets its tokens from your server, as on the web.

On this page