> ## Documentation Index
> Fetch the complete documentation index at: https://docs.embededitor.com/llms.txt
> Use this file to discover all available pages before exploring further.

# How the AI Works

> The editor's AI end to end: which of your functions each feature calls, how they work together, the models that did best in our measurements, and what each thing a person does costs.

<video autoPlay muted loop playsInline src="https://mintcdn.com/feliperohde/AfjjkfPM_42cL5VY/images/ai-annotate.mp4?fit=max&auto=format&n=AfjjkfPM_42cL5VY&q=85&s=3c3156a98b7bcfb72fface8a80552d21" />

The **Annotate** mode asked for a travel guide to Porto, in Corsica: a title and labels on the Genoese tower, the hotels, the marina and the beach, every piece editable. Claude Sonnet 5.5's real answers, played four times as fast as they came.

The editor's AI does what the person asks with the editor's own tools: it places arrows, texts, shapes and numbers, crops, adjusts, obfuscates. Everything it makes stays editable, and one Undo takes a whole request back.

It works on the photo's pixels too. The person marks an area with the AI's brush, then removes what is there or generates something new in it, from words or from an image; or takes the photo's background off, and paints a new one in its place. What it paints becomes part of the photo, one undo step each.

The editor holds no key and runs no model. Each AI job is a function you give it, which posts to your server, where your key stays. You pick the models, and the bill is yours. This page shows how those functions work together, which models we recommend after measuring them, and what each thing a person does costs. Each function's own page has the details and a ready server for every model, in TypeScript that compiles as printed in a new Next.js app, whose settings target ES2017.

The editor sends each function one request, the same whichever model your server calls, and takes back an answer of any size. Your server, the one part of your integration that knows its model, adapts that request to it: one model takes only certain sizes, another a box in place of the mask, another the photo and the widths of the borders to add. So you can change the model, or the provider, with no new version of the editor. [What the Editor Sends, What Your Server Adapts](https://docs.embededitor.com/ai/on-ai-edit-image.md#what-the-editor-sends-what-your-server-adapts) shows it for the fill, model by model, and the image library the servers adapt it with.

> [!NOTE]
>
> Full and Trial only. The Free and the Lite accept the AI's props and ignore them.

## The Layers

| Function | What it receives and returns | What it enables |
| - | - | - |
| [`onAiChooseCommands`](https://docs.embededitor.com/ai/on-ai-choose-commands) | The conversation and available tools; returns the model's next message. | Requests in **Edit** and **Annotate**, and the AI commands `ask.send()`, `annotate.create()` and `annotate.recreate()`. |
| [`onAiDetectObjects`](https://docs.embededitor.com/ai/on-ai-detect-objects) | A photo and the kinds to find; returns a box for each find. | **Detect**, including the model's `obfuscate_detect` tool. |
| [`onAiEditImage`](https://docs.embededitor.com/ai/on-ai-edit-image) | The photo or an area, its mask where needed, words and a reference image; returns the edited image. | **Remove Object**, pixel **Generate**, a new background and **Expand**, including the model's fill tools. |
| [`onAiRemoveBackground`](https://docs.embededitor.com/ai/on-ai-remove-background) | A photo and optional words describing what to keep; returns a PNG with a transparent background. | **Remove Background**, including the model's `retouch_remove_background` tool. |

The person opens the AI with ✦. Closing it keeps the conversation, typed words and marked areas for when it opens again. Your code can open and close it with `ask.open()` and `ask.close()`.

![The AI open in Edit over a living room: the plant and the vase on the coffee table under an area brushed in the brush's colors; the selector's Edit, Remove Object, Remove Background and Annotate, with the lit ✦ drawn as an ✕ at their row's end; the Brush and Eraser beside the field, which starts with the Examples question mark and holds A glass vase of red roses on the coffee table; Generate beside it, and the brush's size, 48 px, under them](https://mintcdn.com/feliperohde/AfjjkfPM_42cL5VY/images/ai-screen.webp?fit=max\&auto=format\&n=AfjjkfPM_42cL5VY\&q=85\&s=58450e55dbda2a8130a49bc89dcbdb1c)

The AI open in **Edit**, a request ready: the plant on the coffee table brushed over, what to put there in the field, **Generate** lit. On a phone, the selector slides, the chosen mode in view.

![The same AI on an iPhone: the living room with the plant brushed over, the selector sliding with Annotate at its edge, the lit ✕ beside it, and the field holding the words, with Generate](https://mintcdn.com/feliperohde/AfjjkfPM_42cL5VY/images/ai-screen-phone.webp?fit=max\&auto=format\&n=AfjjkfPM_42cL5VY\&q=85\&s=8e4a57f66505f5d57e72f3d38b30a867)

The selector offers the modes your functions enable: **Edit** with `onAiChooseCommands` or `onAiEditImage`, **Remove Object** with `onAiEditImage`, **Remove Background** with `onAiRemoveBackground`, and **Annotate** with `onAiChooseCommands` and Annotate on. With `enableAiRemoveBackgroundPrompt`, the person can describe what to keep.

![Porto's bay in Corsica from above, annotated by the AI's Annotate mode: the title Porto, Corsica, Travel guide, a magnifier with an orange rim on the Genoese tower, orange outlines round two hotels, and white cards with orange lines: Genoese tower; Hotels, Terracotta rooftops above the bay; Marina, Harbor moorings; Beach, Sand and pebbles; the AI open on Annotate, its card folded to a pill with the request's words, the request in the field](https://mintcdn.com/feliperohde/AfjjkfPM_42cL5VY/images/ai-annotate.webp?fit=max\&auto=format\&n=AfjjkfPM_42cL5VY\&q=85\&s=d35edb440b7690b72c105a467f23ce42)

The **Annotate** mode's guide to Porto, finished, its card folded to the pill with the request's words. Claude Sonnet 5.5's real composition.

![The same travel guide on an iPhone: the title and the four labels on the bay, the card folded to its pill above the photo, the selector on Annotate and the field holding the request](https://mintcdn.com/feliperohde/AfjjkfPM_42cL5VY/images/ai-annotate-phone.webp?fit=max\&auto=format\&n=AfjjkfPM_42cL5VY\&q=85\&s=92e1e53346f6d6f27063947ad4c7bf37)

The AI’s card shows its work, reply or failure. The person can stop work, fold the card or close it.

The AI offers examples for the functions and tools you enable. Choosing one fills the field without sending it; you can change the examples through `lang.texts` (`aiExample` keys).

`onAiChooseCommands` is the one that makes the AI talk. The other functions work alone too: a site that gives only `onAiEditImage` gets the brush with **Edit** and **Remove Object**, one that gives only `onAiRemoveBackground` gets **Remove Background** alone, one that gives only `onAiDetectObjects` gets **Detect**, and with `onAiChooseCommands` beside them the AI's conversation removes, generates, cuts and detects through them.

## The Annotate Mode at Work

Each of these jobs started as a request in **Annotate** and was finished by hand where needed. Every piece remains editable. [Use Cases](https://docs.embededitor.com/ai/use-cases.md) shows more examples.

![A white car after a front-end crash, annotated: sketchy red outlines round the crumpled hood and fender and the torn-open front end, red Numbers 1 to 4 on them, the detached underbody panel and the bumper debris, their words in a list titled Damage points, a yellow ruler beside the front end labeled ≈ 50 cm, and a magnifier on the side mirror hanging off, under the label Mirror broken off; under it, the request](https://mintcdn.com/feliperohde/AfjjkfPM_42cL5VY/images/ai-annotate-car-damage.webp?fit=max\&auto=format\&n=AfjjkfPM_42cL5VY\&q=85\&s=7c287866c31dd5965db79592070af590)

Insurance and car rental

![The west front of Notre-Dame de Paris, annotated: the title Notre-Dame de Paris, Gothic west façade, a magnifier on the Gallery of Kings with its card, 28 kings of Judah, and yellow Numbers on the twin towers, the arcaded gallery, the rose window and the three portals, their words in a list titled Gothic façade; under it, the request](https://mintcdn.com/feliperohde/upG7bjEmk-qJmOys/images/ai-annotate-cathedral-architecture.webp?fit=max\&auto=format\&n=upG7bjEmk-qJmOys\&q=85\&s=7e36be55472c48fd822ecab8f96255a8)

Education

![An orange prototype through a corner at Le Mans, annotated: an orange highlighter stroke from ahead of the car past the inside kerb to the corner's exit, orange Numbers 1 to 3 on the braking point, the apex and the exit, their words in a list titled Racing line with a line each: Brake in a straight line, Clip the inside kerb, Use the whole track; under it, the request](https://mintcdn.com/feliperohde/AfjjkfPM_42cL5VY/images/ai-annotate-racing-line.webp?fit=max\&auto=format\&n=AfjjkfPM_42cL5VY\&q=85\&s=d9163f476917d55c68f2508db7e3d75f)

Track days and driving schools

## How a Request Flows

```mermaid theme={"dark"}
sequenceDiagram
    participant Person
    participant Editor
    participant Chat as Your onAiChooseCommands
    Person->>Editor: "Point out the ingredients"
    loop Each round, until the model answers in words
        Editor->>Chat: The conversation and the tools
        Chat-->>Editor: Words, tool calls, or both
        Editor->>Editor: Runs each call as a command (read_screenshot, annotate_add…)
    end
    Editor-->>Person: The finished composition, one undo step, and the AI's reply
```

1. The person asks, in **Edit** or in **Annotate**.
2. The editor calls `onAiChooseCommands` with the conversation and the tools.
3. The model looks at the photo with `read_screenshot`, to see where each thing is.
4. The model places each piece with the editor’s commands. The person sees the changes and can stop the request.
5. It looks again, zooming in on each number and arrow tip it placed, fixes what it doesn't like, and answers in words. That answer is the reply the person reads.

A request plays at most 30 rounds. The next request goes on in the same conversation, so "make the 2 bigger" works, in **Edit** and in **Annotate** alike, until another image opens or your `ask.end()` ends it.

### With a Mark

```mermaid theme={"dark"}
sequenceDiagram
    participant Person
    participant Editor
    participant Chat as Your onAiChooseCommands
    participant Fill as Your onAiEditImage
    Person->>Editor: Brushes over a glass, writes "a small glass vase with red roses", taps Generate
    Editor->>Chat: The conversation, the words and the marked areas' boxes
    Chat-->>Editor: A call to retouch_run on the mark
    Editor->>Fill: The piece of the photo around the mark, its mask and the words
    Fill-->>Editor: The image
    Editor->>Editor: Pastes the first into the mark alone
    Editor->>Chat: The call's result
    Chat-->>Editor: Words: what it did
    Editor-->>Person: The vase on the photo and the AI's reply on the card, one undo step
```

1. The person marks an area with the **Brush**, writes what to put there or adds a reference image, then taps **Generate**. In **Remove Object**, they mark the area and tap **Remove**.
2. With `onAiChooseCommands`, a **Generate** in words goes through the conversation: the model gets the words with the marked areas' boxes in the photo's px and is told to remove them with `retouch_remove` or generate in them with `retouch_run`, both of `{ "kind": "MARK" }`, which changes exactly the marked pixels, among anything else the words ask (never annotating: the **Annotate** mode is the one way to annotate with the AI). A **Remove Object**, a **Generate** with an image, every **Generate** without `onAiChooseCommands`, and, with it, **Generate** pressed again with the same words over the same areas go straight to `onAiEditImage`.
3. `onAiEditImage` gets the piece of the photo around the mark, its mask, the words and the image, and gives back the image it made. With nothing marked, a request that adds or changes something sends it the whole photo with no mask (`'EDIT_PHOTO'`), and its image lands over the whole photo.
4. The editor pastes the image into the mark alone, its edge feathered and its color matched to the photo around it; outside the mark, every pixel stays as it was. **Generate** pressed again over the same areas, or `retouch.more()`, asks for another in its place, each one undo step: Undo walks back through them. With `onAiChooseCommands`, that holds for the same words, the image asked again as the model asked for it; other words go to the model, as step 2 says.

**Remove Background** has no brush: its **Remove** goes straight to `onAiRemoveBackground` with the photo, and keeps only the alpha it gives back. Then, with `onAiEditImage`, the mode's row is the new background's field and its **Generate**, which has `onAiEditImage` paint it under the subject. That **Generate** goes as a **Generate** on a mark does: in words, through the conversation with `onAiChooseCommands`, the model told the background by its own kind and its box, never as a mark, and writing the fill's words in English; without `onAiChooseCommands`, straight to `onAiEditImage`. Either way the new background goes under the whole subject.

## What We Recommend

These models did best in our measurements. Bria makes several models for different jobs; fal and Runware are providers that run them. The mixed server uses both providers, and [onAiEditImage](https://docs.embededitor.com/ai/on-ai-edit-image.md#servers) also has a server for each provider alone.

| What the person does | Recommended model and provider |
| - | - |
| [Request an edit or compose annotations](https://docs.embededitor.com/ai/on-ai-choose-commands.md#which-model) | Claude Sonnet 5.5 · Anthropic |
| [Detect faces, plates, documents and screens](https://docs.embededitor.com/ai/on-ai-detect-objects.md#which-model) | SAM 3 · fal |
| [Remove an object](https://docs.embededitor.com/ai/on-ai-edit-image.md#which-model) | Bria Eraser · fal |
| [Generate in a mark from words](https://docs.embededitor.com/ai/on-ai-edit-image.md#which-model) | FLUX.1 Fill \[pro] · Runware |
| [Put a reference image in a mark](https://docs.embededitor.com/ai/on-ai-edit-image.md#which-model) | Seedream 5.5 · Runware |
| [Put a reference image on a new background](https://docs.embededitor.com/ai/on-ai-edit-image.md#which-model) | FLUX 3 Image · Runware |
| [Expand a photo](https://docs.embededitor.com/ai/on-ai-edit-image.md#which-model) | Bria FIBO Edit 1.5 Expand · fal |
| [Generate a new background from words](https://docs.embededitor.com/ai/on-ai-edit-image.md#which-model) | Bria FIBO 2.0 Edit · Runware |
| [Edit the whole photo](https://docs.embededitor.com/ai/on-ai-edit-image.md#which-model) | Seedream 5.5 · Runware |
| [Remove the background](https://docs.embededitor.com/ai/on-ai-remove-background.md#which-model) | Bria RMBG 2.0 · fal |

Each function's page compares alternatives and has ready servers. Bria FIBO 2.0 Edit is also available on fal: in our tests it gave comparable results and was faster there.

## What It Costs

| What the person does | Calls | With the recommended models |
| - | - | - |
| One request in **Annotate** (a composition) | `onAiChooseCommands`, about eight rounds | About US\$ 0.13 and 46 seconds with Claude Sonnet 5.5, measured on 2026-11-21; under a cent with Claude Haiku 5.5, measured on 2026-11-11 with the guide before |
| One **Detect** | `onAiDetectObjects`, one call, the photo at 1024 px | US\$ 0.02 and 2.7 to 4.7 seconds with SAM 3 on fal; about US\$ 0.0012 with Moondream 3 on fal |
| One **Remove Object** | `onAiEditImage`, one call | US\$ 0.04 and 14 to 22 seconds with Bria Eraser on fal |
| One **Generate** in words, or `retouch.more()` | `onAiEditImage`, one call, and with `onAiChooseCommands` the request's rounds | US\$ 0.05 and 7 to 10 seconds with FLUX.1 Fill \[pro] on Runware, plus the rounds |
| One **Generate** with an image | `onAiEditImage`, one call | US\$ 0.044 and about 30 seconds with Seedream 5.5 on Runware, measured on 2026-11-27 |
| One **Expand**, or its **Generate Again** | `onAiEditImage`, one call | US\$ 0.04 and about 21 seconds with Bria FIBO Edit 1.5 Expand on fal |
| One **Remove Background** | `onAiRemoveBackground`, one call | US\$ 0.018 and 7 to 17 seconds with Bria RMBG 2.0 on fal; with the person's words, US\$ 0.03 and 30 to 40 seconds |
| One new background's **Generate** | `onAiEditImage`, one call, and with `onAiChooseCommands` the request's rounds | US\$ 0.04 and 21 to 33 seconds with Bria FIBO 2.0 Edit on Runware, plus the rounds |
| One **Generate** with nothing marked that edits the whole photo | `onAiEditImage`, one call, and with `onAiChooseCommands` the request's rounds | US\$ 0.043 and 31 to 41 seconds with Seedream 5.5 on Runware, measured on 2026-11-26, plus the rounds |

An AI request costs by its rounds, as one in **Annotate** does, and each fill or cut it asks for adds that call's price. Each round sends the conversation so far, so the servers keep the provider's cache on: in our measurements about 90% of the input came from the cache, at a tenth of its price. A fill's and a cut's times are your server's, from the editor's call to its answer, the uploads included. The costs above are at the providers' prices of November 2026.

## Your Keys

Each function posts to your server, and only your server holds a key: the editor and the page never see one. Your server is also where you choose the model, limit who may use the AI, and count what each person spends.

## On Cloudflare Workers

The servers on these pages run as they are printed on Node and on Cloudflare Workers: their image work goes through photon, which is WebAssembly, where sharp, being native code, would run on Node alone. The editor's playground runs them on both. On a Worker, they need two things:

* **The Workers Paid plan.** Workers Free gives a request 10 ms of CPU, and past it Cloudflare stops the Worker and answers its error 1102. A fill's image work takes far more: from under 0.05 s of CPU (FLUX 3 Image's box) to about 0.87 s (FLUX Outpainting's whole call on a 2048 × 2048 canvas), and about 0.25 s for the cut every Expand makes, measured on Node ([What the Editor Sends, What Your Server Adapts](https://docs.embededitor.com/ai/on-ai-edit-image.md#what-the-editor-sends-what-your-server-adapts)). Workers Paid gives a request 30 s of CPU, up to 5 minutes with `limits.cpu_ms` in your Wrangler file. The wait for the model, the seconds a fill takes, uses no CPU: it counts toward neither the limit nor the bill.
* **Node.js compatibility.** The servers use `Buffer`, and read their keys from `process.env`. A Worker has both with a compatibility date of 2026-08-04 or later. On an earlier date, add the compatibility flag `nodejs_compat`, and before 2025-04-01 `nodejs_compat_populate_process_env` too, which puts your secrets in `process.env`.

A Worker's isolate holds 128 MB, its WebAssembly memory included, and photon's memory never shrinks once grown. It grows to about 110 MB on FLUX Outpainting's call on a 2048 × 2048 canvas, about 70 MB on the cut every Expand makes, and under 60 MB on the other fills, measured on Node. Past 128 MB, Cloudflare lets the requests in flight finish and starts a new isolate for the next ones.

On a Worker, the person's **Stop** reaches the model's call only if the route does four things, as the playground's routes do:

* **Answer at once, and write while the call runs.** A Worker learns that the page let go of a request only when it writes to it. An answer sent whole at the end never hears the **Stop**: once the page has left, Cloudflare ends the Worker's work outright, so fal's cancel is never sent. So the route answers 200 at once, writes a space every quarter of a second, then the JSON, which takes spaces before its value; the request's `signal` then aborts at the next space after the **Stop**. Before the compatibility date 2026-11-17, it aborts only with the compatibility flag `enable_request_signal`.
* **Put a call's error in the body.** The status is sent before the call ends, so a failure answers `{ error }` in the 200, and the page reads it there: `if (answer.error) { throw new Error(answer.error); }`.
* **Keep the work with `waitUntil`.** The page leaving ends whatever of the Worker's work `ctx.waitUntil` doesn't hold, so the route holds the call until it has stopped.
* **Wait for fal's cancel.** A Worker drops a request still in flight once its own request has ended, so [`fal-job.ts`](https://docs.embededitor.com/ai/on-ai-edit-image#the-fal-job) waits for fal's answer to the cancel before the call rejects.

Here is [the chat's route](https://docs.embededitor.com/ai/on-ai-choose-commands.md#wire-it) that way, its answer the same message; the other routes wrap their call alike, the fill answering its image as a data URL in the JSON, as the playground does. The editor's own tests run this file as printed:

```ts worker.ts theme={"dark"}
import type { ChatMessage, ChatTool } from '@embededitor/full/react';

import claude from './claude';

// The chat's route on a Cloudflare Worker, so the person's Stop reaches the model's call there: a Worker learns that the
// page let go of a request only when it writes to it, so the route answers at once and writes while the call runs, the
// call's JSON after the spaces, which JSON takes before its value. The status is sent before the call ends, so a call that
// rejects answers `{ error }` in the 200. The other routes wrap their call alike

// what a Worker's handler gets after the request and its env, as much of it as the route uses (ExecutionContext)
type Context = { waitUntil: (promise: Promise<unknown>) => void };

// the time between two of the spaces an answer writes while its call runs, in ms
const BEAT_MS = 250;

const encoder = new TextEncoder();

// `work`'s JSON, answered at once: a space every BEAT_MS while it runs, then what it gives, or `{ error }` where it
// rejects. `ctx.waitUntil` keeps the work running past the page leaving, until the call has stopped
const answered = ({ ctx, work }: { ctx: Context; work: () => Promise<unknown> }) => {
	const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>();
	const writer = writable.getWriter();
	const beat = setInterval(async () => {
		try {
			await writer.write(encoder.encode(' '));
		} catch {
			// the page left: no one reads it
		}
	}, BEAT_MS);
	const done = (async () => {
		const payload = await settled(work);

		clearInterval(beat);

		try {
			await Promise.all([writer.write(encoder.encode(JSON.stringify(payload))), writer.close()]);
		} catch {
			// the page left: no one reads it
		}
	})();

	ctx.waitUntil(done);

	return new Response(readable, { headers: { 'content-type': 'application/json' } });
};

// what `work` gives, or `{ error }` with its message where it rejects
const settled = async (work: () => Promise<unknown>) => {
	try {
		return await work();
	} catch (err) {
		return { error: (err as Error).message };
	}
};

export default {
	// the Worker's answer to `request`: the page's round sent to Claude Sonnet 5.5 (claude.ts), the request's signal its
	// call's. `env` goes unread (the key is in process.env), but a Worker's handler takes it before `ctx`
	fetch: (request: Request, env: unknown, ctx: Context) => {
		return answered({
			ctx,
			work: async () => {
				const { messages, tools }: { messages: ChatMessage[]; tools: ChatTool[] } = await request.json();
				const { message } = await claude.chooseCommands({ messages, model: 'claude-sonnet-5-5', signal: request.signal, tools });

				return message;
			}
		});
	}
};
```

Even then, a **Stop** drops only a job fal hasn't started: one already running finishes and is billed, on any host ([the fal job](https://docs.embededitor.com/ai/on-ai-edit-image.md#the-fal-job)).

A server on Node needs none of this: Node hears the page leave at once, whether or not the answer has started.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.