> ## 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.

# onAiRemoveBackground

> Let the editor's AI take the background off the photo: what the editor sends, what it takes back, which model did best in our measurements, and servers ready for Bria RMBG 2.0, BiRefNet v2 and Cloudflare Images.

`onAiRemoveBackground` takes the background off the photo. With it, the AI offers **Remove Background** on its selector, with no brush and one button, **Remove**, a tip on the photo saying it removes the background and keeps the main subject: one tap, and the photo's subject stands on a transparent background, shown as a checkerboard; saved as a PNG or a WebP, it stays transparent, and as a JPEG, it comes out white. After it, with [`onAiEditImage`](https://docs.embededitor.com/ai/on-ai-edit-image), the mode's row is the new background's field, **Describe the new background**, and its **Generate** has the fill paint it in, your function told it is the new background by its [`operation`](https://docs.embededitor.com/ai/on-ai-edit-image#what-the-editor-sends), `'GENERATE_BACKGROUND'`, which the recommended server sends, in words, to Bria FIBO 2.0 Edit, the model that followed the words in our measurements; without `onAiEditImage`, the cut photo leaves **Remove** alone, off, until an Undo brings the uncut photo back. With it, the AI's conversation gets the `retouch_remove_background` tool too, and [`retouch.removeBackground()`](https://docs.embededitor.com/api-reference/commands/ai#removebackground) runs it from code. Without it, the button doesn't show.

<video autoPlay muted loop playsInline src="https://mintcdn.com/feliperohde/97uFNfnZlTo37nAH/images/ai-remove-background.mp4?fit=max&auto=format&n=97uFNfnZlTo37nAH&q=85&s=cbdfcc16e9c6c78253939942d837f8e4" />

**Remove**, and the woman with her maple leaf stands on the checkerboard, the autumn street behind her gone, her loose hair cut strand by strand; then a new background in words, a golden larch forest by an alpine lake in soft light, painted behind her, her outline as the cut left it. Bria RMBG 2.0's, Claude Sonnet 5.5's and Bria FIBO 2.0 Edit's real answers, played four times as fast as they came.

![A woman in a cream knit sweater holding an orange maple leaf over her face, in three steps: on a street of blurred autumn trees, labeled Original; on the checkerboard with the street taken off, labeled Background removed; and before a golden larch forest by an alpine lake in soft light, labeled with the words that asked for it, A golden larch forest by an alpine lake, autumn, soft light](https://mintcdn.com/feliperohde/97uFNfnZlTo37nAH/images/ai-new-background.webp?fit=max\&auto=format\&n=97uFNfnZlTo37nAH\&q=85\&s=59ac4ef9c491321dc7280f50605a4978)

The photo, its street removed, then a new background asked in words, the woman as the cut left her. Bria RMBG 2.0's, Claude Sonnet 5.5's and Bria FIBO 2.0 Edit's real answers.

For a business, a product photo made where the product sells: a car dealer's SUV on a coastal road at sunset, its features then called out in **Annotate**; a cosmetics brand's serum on water and petals, then **Expand** to a 16:9 banner; a race car in a pit lane at night, expanded to 16:9. The same real models, with Bria FIBO Edit 1.5 Expand for the borders; their commands in [Use Cases](https://docs.embededitor.com/ai/use-cases.md).

![A matte black SUV parked against a gray concrete wall, labeled Original; the SUV alone on the checkerboard, labeled Background removed; and under them the SUV on a coastal road at sunset, the sea and the cliffs behind it, and black labels with orange dots and lines: Slim headlights, Tinted windows, Slim tail lights and Aero wheels, labeled with the two requests](https://mintcdn.com/feliperohde/upG7bjEmk-qJmOys/images/ai-car-coastal-road.webp?fit=max\&auto=format\&n=upG7bjEmk-qJmOys\&q=85\&s=93025a683318349741b00dcbc4fb6076)

![An amber dropper bottle with a blank label on a concrete block against a beige wall, labeled Original; the bottle and its block on the checkerboard, labeled Background removed; and under them a 16:9 banner, the bottle on its block over still water rippling round it, white petals floating on it, labeled with the request and the ratio](https://mintcdn.com/feliperohde/AfjjkfPM_42cL5VY/images/ai-serum-banner.webp?fit=max\&auto=format\&n=AfjjkfPM_42cL5VY\&q=85\&s=d25b0e353d403c52dd879bd42fb38369)

![A yellow and blue stock car seen from behind on a banked track, labeled Original; the car alone on the checkerboard, labeled Background removed; and under them a 16:9 banner, the car on a wet pit lane at night between lit garages and stacks of tires under floodlights, labeled with the request and the ratio](https://mintcdn.com/feliperohde/AfjjkfPM_42cL5VY/images/ai-race-car-pit-lane.webp?fit=max\&auto=format\&n=AfjjkfPM_42cL5VY\&q=85\&s=77ec3f68dfc47d90549148decf525571)

<video autoPlay muted loop playsInline src="https://mintcdn.com/feliperohde/97uFNfnZlTo37nAH/images/ai-showcase-sneaker-banner.mp4?fit=max&auto=format&n=97uFNfnZlTo37nAH&q=85&s=931205ecdebb40bc004d39ec9b819920" />

A whole job, the online store's banner ([Use Cases](https://docs.embededitor.com/ai/use-cases.md#online-store)): the sneaker cut from its orange backdrop, a wet street at night with neon reflections painted behind it, **Expand** to 16:9, and its three selling points called out. The models' real answers, played four times as fast as they came.

> [!NOTE]
>
> Full and Trial only. The Free and the Lite accept `onAiRemoveBackground` and ignore it. It works alone: a site that gives only this function gets the AI's ✦ and **Remove Background**'s **Remove**, with no selector, and nothing more.

## Wire It

In the page, `onAiRemoveBackground` posts the photo to your server and reads the cut back:

```ts page.ts theme={"dark"}
import type { EmbedEditorProps } from '@embededitor/full/react';

// the AI's background removal through your server's route (route.ts)
const onAiRemoveBackground: EmbedEditorProps['onAiRemoveBackground'] = async ({ image, prompt, signal }) => {
	const body = new FormData();

	body.append('image', image);
	body.append('prompt', prompt);

	const res = await fetch('/api/ai-remove-background', { body, method: 'POST', signal });

	if (!res.ok) {
		throw new Error('The background removal failed.');
	}

	return res.blob();
};
```

On your server, a route takes the background off through one of [the servers below](#servers), here as a Next.js route handler:

```ts route.ts theme={"dark"}
import background from './background';

export const POST = async (request: Request) => {
	const form = await request.formData();
	const image = form.get('image');
	const prompt = form.get('prompt');

	if (!(image instanceof Blob)) {
		return new Response('No image', { status: 400 });
	}

	const res = await background.removeBackground({ image, prompt: typeof prompt === 'string' ? prompt : '', signal: request.signal });

	return new Response(res.image, { headers: { 'content-type': res.image.type } });
};
```

Pass the function to `EmbedEditor`, or as the same option of `mountEditor` and `openEditor`.

## What the Editor Sends

```ts theme={"dark"}
onAiRemoveBackground?: (input: { image: Blob; prompt: string; signal: AbortSignal }) => Promise<Blob>;
```

**image** `Blob`

A JPEG of the photo as it is at that moment, at most 2048 px on its longer side: the photo with the AI's own edits, such as an earlier fill, and none of the rest: no crop, rotation, adjustments, filter, frame, annotations or Obfuscate areas, and no mark of any kind, the badge included. So the cut fits the whole photo, even when the person crops it afterward.

**prompt** `string`

What to keep, in words, as the person typed them in Remove Background's own field, **Describe what to keep**, before tapping its **Remove** (`'the woman and her dog'`), for a model that cuts by words. Only with [`enableAiRemoveBackgroundPrompt`](https://docs.embededitor.com/api-reference/props#ai), with which the tip on the photo says **Leave it blank to keep the main subject**; `''` with no words and without it. The words leave the field as the call goes, and come back to it when your function rejects or its cut separates nothing, for another try with other words. Once the photo is cut, without `onAiEditImage`, the field gives way to **Remove**, off, until an Undo brings the uncut photo back. `retouch.removeBackground({ prompt })` sends them too, and rejects with `NOT_AVAILABLE` for words without the prop. Of [the servers below](#servers), only Bria RMBG 2.0's reads them: turn the prop on with it.

**signal** `AbortSignal`

Aborts when the request stops: the **Stop** on the AI's card, Escape, `ask.stop()` or `ask.end()`, the editor closing or leaving the page, or another image opening. Pass it on to your `fetch` and to your model's call.

## What It Gives Back

The photo with its background transparent: a PNG, or any image with alpha the browser reads, such as a WebP, at any size. The editor uses its alpha alone, stretched to the photo, and keeps the photo's own pixels, so the subject's edge is the one your model drew, hair and fur included.

Where your model separates almost nothing (less than 0.5 % of the pixels below half alpha, or less than 0.5 % at half or above), the editor says Nothing Found and keeps the photo as it was; where the brush shows, it points the person to marking it by hand.

The cut is one undo step. Its pixels are part of the photo, never of the state a host keeps: Save's `src` holds them.

When your function rejects, the AI's card says **Couldn’t Remove the Background**, with your error's message under it, and the photo stays as it was. A rejection that is no `Error`, an `Error` with no message, or one of the editor's own (`EmbedEditorError`) shows **Try again.** under the title, and so does an answer that is no image. `retouch.removeBackground()` rejects with `AI_FAILED` in each case, your error as its `cause` when it rejected. Inside a request, when the model calls its `retouch_remove_background` tool, the card shows neither: the model gets the failure, or the nothing found, as its tool's answer.

## Which Model

We tested the models on three photos on 2026-11-08, then tested additional models on two editor requests on 2026-11-09. We graded the cuts by eye; the sample is small, so try the models on your own images too.

| Model | Provider | Result | Time | Cost per call |
| - | - | - | - | - |
| Bria RMBG 2.0 | fal or Runware | Clean edges on hair, fur and products; takes words describing what to keep. | 7 to 17 s through the editor; 30 to 40 s with words | US\$ 0.018; US\$ 0.03 with words |
| BiRefNet v2 | fal | Faster and cheaper, with softer edges. | 1 to 2 s, model only | about US\$ 0.0003 |
| Cloudflare Images | Cloudflare Workers | No other provider or key; the chosen subject can differ from Bria's. | 1.1 s in our Worker test | US\$ 0.0005 past the plan's free transformations |

**Bria RMBG 2.0** is our recommendation. **BiRefNet v2** is the inexpensive alternative; **Cloudflare Images** is an option when your server runs on Workers. Prices are from November 2026. The time for Bria includes the editor's uploads; the other times do not measure the same path.

## Servers

Each server is one module for your server, with the same `removeBackground` function: it takes the editor's `image` and `signal`, Bria RMBG 2.0's its `prompt` too (Cloudflare Images' takes the Worker's `env` in place of `signal`), and resolves to `{ cost, image }`, the photo with its background transparent and what the call cost, in US\$. The fal servers' calls have two minutes, past which they reject with "The model took too long." The person's Stop ends the wait at once and asks fal to cancel the job, which fal's own client doesn't do: fal drops a job it hasn't started yet but finishes, and bills, one it has ([the fal job](#the-fal-job)).

### Bria RMBG 2.0

Bria's RMBG 2.0, through fal. The photo goes up to fal's storage, then one job, run by [`fal-job.ts`](#the-fal-job), gives the cut back. The words of what to keep go to the same endpoint, which then cuts by them: on our plate, "the plate with the food and the hand" added the whole hand. They cost US\$ 0.03 a call, against 0.018 without. It needs `@fal-ai/client` and `FAL_KEY`. The editor's playground runs this file, word for word.

```ts background.ts theme={"dark"}
import { fal } from '@fal-ai/client';

import falJob from './fal-job';

// The editor's onAiRemoveBackground on Bria RMBG 2.0, through fal, for the site's server, where the key stays (FAL_KEY):
// the photo goes up to fal's storage, then one job (fal-job.ts runs it, with its time limit and its cancel on a stop) gives
// it back as a PNG with the background transparent, with what the call cost, at fal's price of November 2026. The words of
// what to keep (the editor's prompt, with enableAiRemoveBackgroundPrompt) go to the same endpoint, which then cuts by them

// fal's endpoint
const ENDPOINT = 'fal-ai/bria/background/remove';
// US$ a call, and a call with words
const PRICE = 0.018;
const PRICE_WORDED = 0.03;

// `image`, the photo the editor sent, with its background transparent, keeping what `prompt` says ('' for none), and the
// call's cost in US$. `signal` stops the call when the person stops
const removeBackground = async ({ image, prompt, signal }: { image: Blob; prompt: string; signal: AbortSignal }) => {
	const url = await fal.storage.upload(image);
	const input = prompt ? { image_url: url, prompt } : { image_url: url };
	const res = await falJob.run({
		endpoint: ENDPOINT,
		signal,
		subscribe: options => {
			return fal.subscribe(ENDPOINT, { ...options, input });
		}
	});
	const cut = await falJob.download({ signal, url: res.data.image.url });

	return { cost: prompt ? PRICE_WORDED : PRICE, image: cut };
};

export default { removeBackground };
```

### BiRefNet v2

BiRefNet v2, through fal, at 1024 px, its job run by [`fal-job.ts`](#the-fal-job). fal bills it by the second it runs, US\$ 0.000575 a second, so the server asks fal how long the call ran, and gives back the cut with no cost (`null`) where fal doesn't say or fails to answer. It needs `@fal-ai/client` and `FAL_KEY`.

```ts background-cheap.ts theme={"dark"}
import { fal } from '@fal-ai/client';

import falJob from './fal-job';

// The editor's onAiRemoveBackground on BiRefNet v2, through fal, for the site's server, where the key stays (FAL_KEY): the
// photo goes up to fal's storage, then one job (fal-job.ts runs it, with its time limit and its cancel on a stop) gives it
// back as a PNG with the background transparent. fal bills it by the seconds it runs, so the server asks fal how long it
// ran for the call's cost, at fal's price of November 2026; the cut comes back whether or not fal says

// fal's endpoint
const ENDPOINT = 'fal-ai/birefnet/v2';
// US$ a second it runs
const PRICE = 0.000575;

// `image`, the photo the editor sent, with its background transparent, and the call's cost in US$ (null where fal doesn't
// say how long it ran). `signal` stops the calls when the person stops
const removeBackground = async ({ image, signal }: { image: Blob; signal: AbortSignal }) => {
	const url = await fal.storage.upload(image);
	const res = await falJob.run({
		endpoint: ENDPOINT,
		signal,
		subscribe: options => {
			return fal.subscribe(ENDPOINT, { ...options, input: { image_url: url, operating_resolution: '1024x1024', output_format: 'png' } });
		}
	});
	const [cut, seconds] = await Promise.all([falJob.download({ signal, url: res.data.image.url }), ranFor({ requestId: res.requestId, signal })]);

	return { cost: seconds === null ? null : seconds * PRICE, image: cut };
};

// how long, in seconds, fal says the job `requestId` ran: null where it doesn't say, or fails to answer
const ranFor = async ({ requestId, signal }: { requestId: string; signal: AbortSignal }) => {
	try {
		const status = await fal.queue.status(ENDPOINT, { abortSignal: signal, requestId });
		const seconds = status.status === 'COMPLETED' ? status.metrics?.inference_time : null;

		return typeof seconds === 'number' ? seconds : null;
	} catch {
		return null;
	}
};

export default { removeBackground };
```

### Cloudflare Images

For a site whose server is a Cloudflare Worker: the Worker's Images binding cuts the subject out with `segment: 'foreground'`, BiRefNet run on Workers AI. Bind Images in the Worker's Wrangler file (`"images": { "binding": "IMAGES" }`), on an Images Paid plan. The binding takes no signal, so the function takes the Worker's `env` in its place: call it from the Worker's `fetch` with the `env` it gets. Cloudflare bills each call as a unique transformation, the first 5,000 a month included, then US\$ 0.50 for 1,000.

Cloudflare says its `segment` runs BiRefNet. On our plate photo it answered in 1.1 s, run with `wrangler dev --remote`, and cut the food alone, where Bria RMBG 2.0 cut the plate with it: see [Which Model](#which-model).

```ts background-cloudflare.ts theme={"dark"}
// The editor's onAiRemoveBackground on Cloudflare Images, for a site whose server is a Cloudflare Worker: the Worker's
// Images binding (`env.IMAGES`, `"images": { "binding": "IMAGES" }` in its Wrangler file) cuts the photo's subject out with
// `segment: 'foreground'` (BiRefNet, on Workers AI), and gives it back as a PNG with the background transparent. Cloudflare
// bills it as a unique transformation: US$ 0.50 for 1,000 past the 5,000 a month the Images Paid plan includes (PRICE).
// On our plate photo (2026-11-09) it answered in 1.1 s and cut the food alone, the plate left out, with a harder edge

// US$ a call, past the transformations the plan includes
const PRICE = 0.0005;

// `image`, the photo the editor sent, with its background transparent, and the call's cost in US$, through the Images
// binding of the Worker's `env` (typed here as the part of Cloudflare's ImagesBinding it calls)
const removeBackground = async ({
	env,
	image
}: {
	env: {
		IMAGES: {
			input: (stream: ReadableStream) => {
				transform: (options: { segment: 'foreground' }) => {
					output: (options: { format: 'image/png' }) => Promise<{ response: () => Response }>;
				};
			};
		};
	};
	image: Blob;
}) => {
	const res = await env.IMAGES.input(image.stream()).transform({ segment: 'foreground' }).output({ format: 'image/png' });
	const cut = await res.response().blob();

	return { cost: PRICE, image: cut };
};

export default { removeBackground };
```

### The fal job

fal's client, when its signal aborts, stops waiting for the job but doesn't cancel it. The fal servers run each job through this module: when the person stops or [the time limit](#the-time-limit) passes, it stops waiting and asks fal to cancel the job by its id, even where the stop comes before fal gives the id, and it fetches the job's image within the same limit. A cancel drops a job fal hasn't started yet. A job fal has already started runs to its end and is billed: fal answers the cancel and finishes the job anyway (on 2026-11-10, a Bria cut canceled 6 seconds in completed at 25.5 seconds). It needs `@fal-ai/client` and `limit.ts` beside it.

```ts fal-job.ts theme={"dark"}
import { fal } from '@fal-ai/client';

import limit from './limit';

// The fal servers' calls (retouch-fal.ts, background.ts, background-cheap.ts, sam3.ts, moondream.ts), for the site's
// server: each job runs within limit.ts's time limit, and when the person stops or the limit passes, the call stops
// waiting and asks fal to cancel the job, since fal's subscribe, on an abort, only stops waiting. fal drops a job it
// hasn't started yet; a job it has started runs to its end, and fal bills it. The image a job made is fetched within
// the same limit, and past it either call rejects in words the editor can show.

// the image fal put at `url`, fetched against `signal` and the time limit
const download = ({ signal, url }: { signal: AbortSignal; url: string }) => {
	return limit.within({
		signal,
		work: async bounded => {
			const res = await fetch(url, { signal: bounded });

			if (!res.ok) {
				throw new Error(`fal's image answered ${res.status}`);
			}

			return res.blob();
		}
	});
};

// fal's answer to `subscribe`, the job it starts on `endpoint` with the options it is given, against `signal` and the
// time limit: at the first of the two, fal is asked to cancel the job by the id it gave, as soon as it gives it where the
// stop came first, and the call rejects once fal has answered the cancel: a server on Cloudflare Workers drops a
// request still in flight once its own has ended. A job fal has started finishes anyway, and is billed
const run = <T>({
	endpoint,
	signal,
	subscribe
}: {
	endpoint: string;
	signal: AbortSignal;
	subscribe: (options: { abortSignal: AbortSignal; onEnqueue: (requestId: string) => void }) => Promise<T>;
}) => {
	return limit.within({
		signal,
		work: async bounded => {
			let requestId = '';
			let canceled: Promise<void> = Promise.resolve();
			const cancel = async () => {
				try {
					await fal.queue.cancel(endpoint, { requestId });
				} catch {
					// a job that ended first has nothing left to cancel
				}
			};
			const abort = () => {
				if (requestId) {
					canceled = cancel();
				}
			};

			bounded.addEventListener('abort', abort, { once: true });

			try {
				return await subscribe({
					abortSignal: bounded,
					onEnqueue: id => {
						requestId = id;

						if (bounded.aborted) {
							canceled = cancel();
						}
					}
				});
			} finally {
				bounded.removeEventListener('abort', abort);
				await canceled;
			}
		}
	});
};

export default { download, run };
```

### The time limit

Every call to a model gets two minutes, its image's fetch included: over twice the slowest call we measured of a model our servers run, Object Eraser's 50 seconds on Runware, which fills a Remove. This module gives the call a signal that aborts when the person stops or the two minutes pass, whichever comes first, and past them rejects with "The model took too long.", the words the editor shows. The fal job and the Runware server both run their calls through it.

```ts limit.ts theme={"dark"}
// The time limit of the servers' calls to a model (fal-job.ts runs fal's, retouch-runware.ts and faces-runware.ts
// Runware's), for the site's server: a call gets a signal that aborts when the person stops or TIMEOUT passes,
// whichever comes first. Past TIMEOUT, it rejects in words the editor can show (TOO_LONG), the timeout kept as its
// cause

// the longest a call, with the fetch of its image, may take, in ms: over twice the slowest call our measurements saw of
// a model the servers run (Object Eraser's 50 s, on Runware) and about twice the slowest of Runware's own examples
// (Object Eraser's 63 s), as long as Runware holds a task on an HTTP call before it answers that it is still running
const TIMEOUT = 120000;
// what a call past TIMEOUT rejects with, as does one its provider ends while the task still runs
const TOO_LONG = 'The model took too long.';

// what `work` gives with a signal that aborts at `signal` or past TIMEOUT, whichever comes first: past TIMEOUT, it rejects
// with TOO_LONG; else with the work's own error
const within = async <T>({ signal, work }: { signal: AbortSignal; work: (bounded: AbortSignal) => Promise<T> }) => {
	const bounded = AbortSignal.any([signal, AbortSignal.timeout(TIMEOUT)]);

	try {
		return await work(bounded);
	} catch (err) {
		if (bounded.aborted && !signal.aborted) {
			throw new Error(TOO_LONG, { cause: err });
		}

		throw err;
	}
};

export { TOO_LONG };
export default { within };
```


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