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

# onAiChooseCommands

> Give the editor's AI a model: what the editor sends your server each round, what it takes back, the rules that keep the conversation valid and cheap, and servers ready for Claude, OpenAI and Gemini.

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

One request in **Edit**, to hide the faces in the background and give the photo a warm golden-hour light: the AI covers the eight faces behind the guitarist with Obfuscate's areas, leaves his alone, and warms the light with Adjust, the editor's own tools, so each change stays editable. Claude Sonnet 5.5's real answers, played four times as fast as they came.

`onAiChooseCommands` is the AI's model. With it, the AI's ✦ stands beside Annotate's button, and its selector offers **Edit**, where the person writes what they want, and **Annotate**, where the AI composes the annotations as an art director, the mode the ✦ opens on inside Annotate. The AI does what it is asked with the editor's own tools, so everything it makes stays editable, and one Undo takes a whole request back. **Edit** is never offered Annotate's tools: the **Annotate** mode is the one way to annotate with the AI. The [AI commands](https://docs.embededitor.com/api-reference/commands/ai.md) do the same from code.

> [!NOTE]
>
> Full and Trial only. The Free and the Lite accept `onAiChooseCommands` and ignore it: no AI shows, and their AI commands reject with `NOT_AVAILABLE`.

The editor holds no key and calls no model itself. Each round, it calls your function with the conversation so far. Your function sends it to your server, where the key stays, and your server asks the model. The model and the bill are yours.

## How a Request Runs

1. The editor calls `onAiChooseCommands` with the conversation and the tools.
2. The model answers with words, with calls to the tools, or with both.
3. The editor runs each call as one of its commands, in order: the change lands on the photo, and the call's result joins the conversation.
4. Back to 1, until the model answers in words alone. That answer is the reply the person reads.

A request plays at most 30 rounds, a round being one call to `onAiChooseCommands`. While it works, the person sees each change land, the AI's card at the top of the photo says what the AI is doing, a light sweeping across its words, and the photo's edge glows in the colors of the AI's brush. When a round runs 15 seconds late, a second line under it says it is taking a little longer than usual; while a tool the model called runs one of your pixel functions (a fill, a cut, a find), the line waits 50 seconds, as those take longer, and once your function answers, the next round gets its 15 seconds again, counted from then.

## Wire It

In the page, `onAiChooseCommands` posts the conversation to your server:

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

// the editor's AI through your server's route (route.ts)
const onAiChooseCommands: EmbedEditorProps['onAiChooseCommands'] = async ({ messages, signal, tools }) => {
	const res = await fetch('/api/ai-choose-commands', {
		body: JSON.stringify({ messages, tools }),
		headers: { 'content-type': 'application/json' },
		method: 'POST',
		signal
	});

	if (!res.ok) {
		// shown under "Couldn’t Complete the Request": your words, in the person's language
		throw new Error('The AI is busy. Try again in a moment.');
	}

	return res.json();
};

const PhotoEditor = ({ src }: { src: string }) => {
	return (
		<div style={{ height: 600 }}>
			<EmbedEditor
				onAiChooseCommands={onAiChooseCommands}
				src={src}
			/>
		</div>
	);
};
```

On your server, a route asks the model through one of [the servers below](#servers). This one is a Next.js route handler; any server that takes the Web's `Request` (Cloudflare Workers, Deno, Bun, Hono) takes the same function. On Cloudflare Workers, write it as [On Cloudflare Workers](https://docs.embededitor.com/ai/overview.md#on-cloudflare-workers) shows, so the person's **Stop** reaches the model's call.

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

import claude from './claude';

export const POST = async (request: Request) => {
	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 Response.json(message);
};
```

The route spends your money: check the person's session and limit the requests, as on any paid endpoint of yours. With `mountEditor` and `openEditor`, pass the same function as their `onAiChooseCommands` option.

The body grows with the request, every screenshot in it. Computed at the editor's JPEG from the prototype's runs, the request with the most screenshot bytes (ten screenshots of a busy street) sends about 2.7 MB on its last round, and a longer request sends more. A platform that caps request bodies needs room for it: Vercel Functions take at most 4.5 MB.

## What the Editor Sends

```ts theme={"dark"}
onAiChooseCommands?: (input: { messages: ChatMessage[]; signal: AbortSignal; tools: ChatTool[] }) => Promise<ChatMessage>;
```

**messages** `ChatMessage[]`

The conversation so far, in OpenAI's Chat Completions shape, the one most services take. Your function gets a copy: what it does to the array never reaches the conversation.

**tools** `ChatTool[]`

The tools the model may call, in the same shape: the editor's commands. See [The tools](#the-tools).

**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 to your `fetch`, and your server to the model's call, so a stopped request stops costing.

The conversation, in order:

1. **The guide**, as a system message: the editor's rules for using its tools, looking at the photo, writing text and composing annotations. It includes the editor's language and changes when the available Annotate tools, language or your `aiPrompts` change. Its parts can be replaced: see [Customize the Prompts](https://docs.embededitor.com/ai/customize-prompts.md).
2. **The person's request**, as a user message. The editor adds context for a marked area, the whole photo or a new background, including its box and the tools to use. Annotate requests also get a line identifying the mode; Generate again asks for another composition. The actual lines can be replaced with `aiPrompts`: see [Customize the Prompts](https://docs.embededitor.com/ai/customize-prompts.md).
3. **Each round**: the message your function returned, as it returned it; a `tool` message for each tool call, its content the command's result as JSON; and, after a turn's tool messages, one user message with that turn's screenshots.
4. **The next request** in the same conversation, as a user message after all of that, the system message as it stands then: the same unless Annotate was turned on or off, the editor's language or your `aiPrompts` changed meanwhile.

A screenshot comes as a JPEG in base64, at most 1024 px on its longer side, the whole photo's and a zoom's alike, with a note that says which part of the photo it shows and how its px map to the photo's px, the px every command takes. The note is the `tool` message's content, and again the text right before its image. For a 3000 × 2000 photo, the first round's answer and what follows it:

```json messages.json theme={"dark"}
[
	{ "content": "You are the AI of Embed Editor, a photo editor embedded in websites. … The editor's language is pt-br.", "role": "system" },
	{ "content": "Annotate the photo for this request, as the art director: Identifique os ingredientes desta receita.", "role": "user" },
	{
		"content": "Olhando a foto",
		"role": "assistant",
		"tool_calls": [{ "function": { "arguments": "{}", "name": "read_screenshot" }, "id": "call_1", "type": "function" }]
	},
	{
		"content": "Screenshot 1024×683 px of the image area x 0–3000, y 0–2000 (image px), the output's x 0–3000, y 0–2000 (read_screenshot's area px). Image px = (0 + sx × 2.9297, 0 + sy × 2.9283).",
		"role": "tool",
		"tool_call_id": "call_1"
	},
	{
		"content": [
			{
				"text": "Screenshot 1024×683 px of the image area x 0–3000, y 0–2000 (image px), the output's x 0–3000, y 0–2000 (read_screenshot's area px). Image px = (0 + sx × 2.9297, 0 + sy × 2.9283).",
				"type": "text"
			},
			{ "image_url": { "url": "data:image/jpeg;base64,/9j/4AAQSkZJRg…" }, "type": "image_url" }
		],
		"role": "user"
	}
]
```

### The Tools

Each tool is one of the editor's commands, as `commands()` gives it, under its name in snake\_case, as OpenAI's format takes no dot: `annotate_add`, `read_screenshot`, and `annotate_add_arrow` for `annotate.addArrow`. Its description says what it does and when it rejects, with an example call (`read_screenshot`'s says how its picture comes: a JPEG at most 1024 px on its longer side, with its note; `read_state`'s that the AI's own edits are pixels the state never holds, an Expand's bigger photo aside, which `read_screenshot` shows), and its `parameters` are its input's JSON Schema, but `retouch_run`'s `area`, which takes `{ "kind": "MARK" }`, `{ "kind": "ALL" }` and `{ "kind": "BACKGROUND" }` alone: a box the model picked went to the fill, which redrew what stood in it, where the whole photo's edit keeps the rest. A `POLYGON` or a `RECT` the model sends is answered `INVALID_COMMAND`, `input.area.kind`, your `onAiEditImage` never asked; your own [`retouch.run()`](https://docs.embededitor.com/api-reference/commands/ai#run) takes them, and the model's `retouch_remove` keeps them, to remove a thing by its box. Annotate's tools carry the manual of every piece there: each field's `description` says what it does on the photo, when to use it, and what it takes where a call leaves it out: a new piece, its tool's last style; an arrow added to a text, an added arrow's default; `annotate_update`, the value it has. Each Annotate tool that places or moves an annotation answers with `boxes`, where each one landed once laid out, in image px ([Where It Landed](https://docs.embededitor.com/api-reference/commands/annotate.md#where-it-landed)), so the model checks overlaps and margins without working out a text's width; Obfuscate's and the marks' tools that place or move an area or a mark answer the same way ([Where It Landed](https://docs.embededitor.com/api-reference/commands/obfuscate-marks.md#where-it-landed)), so it checks what an area covers.

* **In:** every command that edits or reads the photo: `obfuscate`, `crop`, `size`, `filter`, `frame`, `adjust`, `auto`, `marks` and the reads, `read_mark` among them, the boxes of the areas the person marked with the AI's brush; the history (`history_undo`, `history_redo`, `history_reset`) and the output (`output_save`, `output_export_file`); and `editor_close` where you give `onClose`, or the editor is `openEditor()`'s modal. `retouch_run`, `retouch_remove` and `crop_expand` are there only when you give [`onAiEditImage`](https://docs.embededitor.com/ai/on-ai-edit-image), `retouch_remove_background` only when you give [`onAiRemoveBackground`](https://docs.embededitor.com/ai/on-ai-remove-background), and `obfuscate_detect` only when you give [`onAiDetectObjects`](https://docs.embededitor.com/ai/on-ai-detect-objects), in a request of `ask.send()`: a request of the **Annotate** mode (`annotate.create()`, `annotate.recreate()`) never changes pixels. A request of `ask.send()` is offered none of Annotate's commands (`annotate_*`) nor `read_options`, and a request of the **Annotate** mode is offered them. An agent over [MCP](https://docs.embededitor.com/mcp/overview.md) is offered the same list with Annotate's commands.
* **Out:** the editor's menu and view (`menu`, `view`), the conversation itself (`ask`), Annotate's `open`, `close`, `create` and `recreate`, and the person's own controls, which change what the person works with next and never the photo: `annotate.select`, `annotate.setStyle`, `annotate.setTheme`, `annotate.setTool`, `obfuscate.select`, `obfuscate.setLook`, `palette.set`, the mark and its brush (`retouch.mark`, `retouch.moveMark`, `retouch.removeMark`, `retouch.erase`, `retouch.unmark`, `retouch.selectMark`, `retouch.setBrush`), the Aspect section's `crop.setMode`, and a Generate or an Expand asked again (`retouch.more`, `crop.more`): the model reads the mark, never makes it.
* **Out too, a tool you turned off:** its commands would only answer `NOT_AVAILABLE`, so they never reach the model. With `enableAnnotate: false` it gets no `annotate_*` tool and no `read_options`; the same goes for `enableFilter`, `enableFinetune` (`adjust` and `auto`), `enableFrame`, `enableObfuscate` and `enableResize` (`size`), and for `marks` while there is no mark the person can adjust (none, or only fixed ones).

Inside a request, the history acts as the person reads "undo that": `history_undo` takes back the request's own last call, whole, and with none made yet the step before the request, as the toolbar's **Undo**; `history_redo` brings them back. The request still ends as one undo step. `output_save` saves as the **Save** button does, `onProcess` and the `save` event included; where Save closes the editor (the modal), and on `editor_close`, the request ends there, the host's onAiChooseCommands asked no more: `ask.send()` rejects `NOT_AVAILABLE` once the editor is gone, as on the person's **Close**, and resolves with its words so far where the editor stays. Nothing the AI makes is selected, and an **Undo** or **Redo** of its step selects nothing it made.

The list is the same on every round of a request, so it caches with the guide. A call that fails is answered as that tool's content, its code and the paths it names, with the schema's issues where the input was off it, `{"code":"INVALID_COMMAND","issues":[…],"props":["input.piece.at"]}`, and the model fixes it: the person never sees it. A linked agent reads the same texts.

## What It Gives Back

The model's next message, in the same shape:

```ts theme={"dark"}
type ChatContentPart = { text: string; type: 'text' } | { image_url: { url: string }; type: 'image_url' };
type ChatToolCall = { function: { arguments: string; name: string }; id: string; type: 'function' };
type ChatMessage = {
	[key: string]: unknown;
	content: string | ChatContentPart[] | null;
	role: 'assistant' | 'system' | 'tool' | 'user';
	tool_call_id?: string;
	tool_calls?: ChatToolCall[];
};
type ChatTool = { function: { description: string; name: string; parameters: Record<string, unknown> }; type: 'function' };
```

**role** `'assistant'`

The model's turn.

**content** `string | null`

Its words, or `null`. Words beside tool calls show on the AI's card as what the AI is doing (the guide asks for one short phrase before each action); without them, the card shows a phrase of the editor's for the tool, such as **Looking at the photo…**. Words alone end the request: they are its reply.

**tool\_calls** `ChatToolCall[]`

The tools it calls, run in order: each with its `id`, the tool's `name` and its `arguments` as the JSON text the model wrote.

Any other field stays on the message, as you returned it. That is where your server keeps what the provider needs back next round: Claude's content with its thinking, OpenAI's items with their reasoning.

A message with neither words nor tool calls ends the request with no reply. It stays in the conversation, as every message does, so leave it out when you send the conversation to the provider: Anthropic's and OpenAI's APIs reject an empty assistant turn that isn't the last. The servers below do.

When your function rejects, the request ends with `AI_FAILED`: the AI's card says **Couldn’t Complete the Request**, with your error's message under it, so write that message for the person, in their language. 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. Either way the request's command (`ask.send()`, `annotate.create()` or `annotate.recreate()`) rejects with `AI_FAILED`, its `cause` your rejection as it came. What the AI did so far stays, as one undo step, and the conversation keeps it. An answer that is no message, or whose `tool_calls` is no list of calls, ends it the same way, with **Try again.** under the title, and stays out of the conversation. An abort through `signal` is a stop, and shows no notice.

## The Rules

* **The conversation only grows.** The editor appends, and never edits or removes a message. The current models reject a history edited around their saved reasoning, and a cache reads only a start identical to the one before. Send the messages to the provider in order, each one every round.
* **Keep what you return whole.** Every message you return comes back to you on the next round exactly as you returned it, extra fields included. Keep the provider's own content there and send it back as it came.
* **The screenshot follows the tool messages.** Chat Completions takes no image in a `tool` message, so `read_screenshot` answers with its note, and the turn's images follow in one user message after that turn's tool messages, each one after its note. Where the provider takes images in a tool's result, as Claude's and OpenAI's Responses APIs do, fold each image into the result its note answers. The servers below do.
* **Cache first.** The guide and the tools repeat on every round, and they are most of what a round sends. Turn the provider's cache on: in the prototype, 89% of the input tokens sent came from the cache, at a tenth of the input price or less on Claude.
* **Add rules the same way every round.** Your server may add its own rules to the system message ("use our brand's colors"). Add them identically on every round, so the start stays cached.
* **A weak model can loop.** The editor stops a request at 30 rounds. A model that can't close the loop of placing, checking and fixing reaches that limit, removing and placing its pieces again. See [Which model](#which-model).
* **One conversation per photo.** The next request goes on in the same conversation, so the model knows what it did ("make the 2 bigger"). Your `ask.end()` ends it, and so does another image opening; the person closing the AI by its lit ✦ keeps it (`ask.close()`).

## Which Model

Choose a model that can use tools and read images. Our recommended server uses **Claude Sonnet 5.5**. In the Annotate bench on 2026-11-21, a composition averaged 46 seconds and US\$ 0.13 over two runs on 12 photos, with about eight rounds per composition. Two blind judges graded the results; these estimates depend on the request and the provider's prices.

* **Claude Sonnet 5.5:** the recommended balance of quality and cost.
* **Claude Opus 5.5:** a more expensive alternative that gave more imaginative compositions in our pilot, measured on four photos.
* **Claude Haiku 5.5:** a cheaper alternative, but its compositions were less consistent. Its cost was under a cent per composition in an earlier test with a different guide.

A model that cannot complete its work may reach the 30-round limit. OpenAI and Gemini have ready servers below, but were not measured through the full Annotate bench.

### Prices

Each server below takes the model as a string, so moving from Sonnet to Haiku or Opus is one word. In US\$ per million tokens, as each provider listed them in November 2026:

| Model | Input | Output | Cache read | Measured in our recipe |
| - | - | - | - | - |
| Claude Sonnet 5.5 | 2 | 10 | 0.10 | Yes: see [Which Model](#which-model) |
| Claude Opus 5.5 | 4 | 20 | 0.20 | Yes, on four photos: see [Which Model](#which-model) |
| Claude Haiku 5.5 | 0.10 (0.50 past 100,000 tokens) | 0.50 (2.50) | 0.01 (0.05) | Yes: see [Which Model](#which-model) |
| GPT-6 Sol | 2 | 10 | 0.20 | No |
| GPT-6 Astra | 10 | 50 | 1 | Pilot only: US\$ 1.16 a composition, pointing at nothing |
| GPT-6 Luna | 0.10 | 0.50 | 0.01 | Pilot only: didn't finish |
| Gemini 3.6 Flash, 3.8 Flash | 0.75 (1.50 from 2027) | 3.75 (7.50 from 2027) | 0.075 (0.15 from 2027) | No |
| Gemini 3.1 Pro (preview) | 2 | 12 | 0.20 | No |

Claude's and Gemini's prices are from their own pricing pages, OpenAI's from its help center's rate table. Each round sends the whole conversation, so the cache read is the price that counts most: in our measurements about 90% of a composition's input came from the cache.

## Servers

Each server is one module for your server, with the same `chooseCommands` function: it takes the editor's `messages` and `tools`, the `model` and the `signal`, sends the conversation in the provider's own shape, and resolves to `{ message, usage }`, the model's answer in the editor's shape and what the round used. Each one:

* sends the system message where the provider wants it;
* sends the tool results the provider's way, each screenshot inside its result where the provider takes it;
* leaves out an assistant message with neither words nor tool calls;
* keeps the provider's own content on the message it gives back, and sends it back as it came;
* has the provider's cache on;
* rejects an answer the model stopped short of (a refusal, or the output limit with a tool call perhaps cut off), so the editor says **Couldn’t Complete the Request** instead of running half a call.

### Claude

The Messages API, each screenshot folded into the `tool_result` it answers, with automatic caching. The editor's own bench runs this file (`yarn editor ai:bench`), word for word. It needs `@anthropic-ai/sdk` and `ANTHROPIC_API_KEY`. `cost()` prices a round at Anthropic's prices of November 2026, for your own metering.

```ts claude.ts theme={"dark"}
import Anthropic from '@anthropic-ai/sdk';

import type { ChatMessage, ChatTool, ChatToolCall } from '@embededitor/full/react';

// The editor's onAiChooseCommands on the Claude API, for the site's server, where the key stays (ANTHROPIC_API_KEY): each round
// the editor sends its conversation, in OpenAI's Chat Completions shape, and `chooseCommands` sends it to Claude as Anthropic's own
// messages, then gives the answer back in the editor's shape. Claude's own content rides along on the message it gives
// back, and goes back to Claude as it came, so its thinking stays valid. Caching is on: each round reads the conversation
// so far from the cache, at a tenth of the input price or less (PRICES)

type Model = keyof typeof PRICES;

// how a data URL names its image type and holds its bytes
const DATA_URL = /^data:([^;,]+);base64,(.+)$/;
// the most a round may write
const MAX_TOKENS = 16000;
// the image types Claude reads
const MEDIA_TYPES = ['image/gif', 'image/jpeg', 'image/png', 'image/webp'] as const;
// US$ per million tokens: input, output, a cache read and a cache write (5 minutes). A Haiku 5.5 round whose prompt is
// over `long.above` tokens, its cache reads and writes counted, pays its `long` prices, the whole round
const PRICES = {
	'claude-haiku-5-5': { input: 0.1, long: { above: 100000, input: 0.5, output: 2.5, read: 0.05, write: 0.625 }, output: 0.5, read: 0.01, write: 0.125 },
	'claude-opus-5-5': { input: 4, long: null, output: 20, read: 0.2, write: 5 },
	'claude-sonnet-5-5': { input: 2, long: null, output: 10, read: 0.1, write: 2.5 }
};

// an assistant message as Claude's content: what Claude gave it, stashed on it by `chooseCommands` (its thinking and signatures
// included), or else its words and tool calls; null for one with neither, which Claude takes no turn for
const assistantContent = (message: ChatMessage): Anthropic.ContentBlockParam[] | null => {
	const calls = message.tool_calls ?? [];
	const words = text(message.content);

	if (!words && !calls.length) {
		return null;
	}

	if (Array.isArray(message.claudeContent)) {
		return message.claudeContent;
	}

	const uses = calls.map((call): Anthropic.ToolUseBlockParam => {
		return { id: call.id, input: toolInput(call.function.arguments), name: call.function.name, type: 'tool_use' };
	});

	return words ? [{ text: words, type: 'text' }, ...uses] : uses;
};

// One round of the editor's conversation on `model`: Claude's answer as the editor's next message, and what the round
// used (`cost` gives it in US$). `signal` aborts the call when the person stops. An answer Claude stopped short of (a
// refusal, or `max_tokens` with a tool call perhaps cut off) rejects: the editor then says Couldn’t Complete the Request and keeps
// what the rounds before did. The client is made here, so a server whose environment exists per request has its key
const chooseCommands = async ({ messages, model, signal, tools }: { messages: ChatMessage[]; model: Model; signal: AbortSignal; tools: ChatTool[] }) => {
	const client = new Anthropic({ maxRetries: 4 });
	const native = toAnthropic(messages);
	const res = await client.messages.create(
		{
			cache_control: { type: 'ephemeral' },
			max_tokens: MAX_TOKENS,
			messages: native.messages,
			model,
			system: native.system,
			tools: tools.map(({ function: { description, name, parameters } }) => {
				return { description, input_schema: { ...parameters, type: 'object' }, name };
			})
		},
		{ signal }
	);

	if (res.stop_reason === 'max_tokens' || res.stop_reason === 'refusal') {
		const category = res.stop_details?.category;

		throw new Error(category ? `Claude stopped: ${res.stop_reason} (${category})` : `Claude stopped: ${res.stop_reason}`);
	}

	return { message: toChatMessage(res.content), usage: res.usage };
};

// what a round cost, in US$: its tokens at `model`'s prices, its long prices where its prompt passes them
const cost = ({ model, usage }: { model: Model; usage: Anthropic.Usage }) => {
	const { long, ...base } = PRICES[model];
	const read = usage.cache_read_input_tokens ?? 0;
	const write = usage.cache_creation_input_tokens ?? 0;
	const price = long && usage.input_tokens + read + write > long.above ? long : base;

	return (usage.input_tokens * price.input + usage.output_tokens * price.output + read * price.read + write * price.write) / 1e6;
};

// the user message the editor sends after a turn's tool messages, folded into their tool_result blocks (`results`): each
// screenshot (an image right after its note) into the next result whose content is that note, and anything else, as the
// words of a request that follows a stopped turn, after the results
const fold = ({ content, results }: { content: ChatMessage['content']; results: Anthropic.ContentBlockParam[] }) => {
	if (typeof content === 'string') {
		return [...results, ...parts(content)];
	}

	const list = content ?? [];
	let after = -1;
	let folded = results;
	let rest: Anthropic.ContentBlockParam[] = [];

	for (let index = 0; index < list.length; index += 1) {
		const part = list[index];
		const next = list[index + 1];
		const shot = part.type === 'text' && next?.type === 'image_url' ? { note: part.text, url: next.image_url.url } : null;
		const at = shot
			? folded.findIndex((block, blockIndex) => {
					return blockIndex > after && block.type === 'tool_result' && block.content === shot.note;
				})
			: -1;

		if (!shot || at === -1) {
			rest = [...rest, ...parts([part])];
			continue;
		}

		folded = folded.map((block, blockIndex) => {
			return blockIndex === at && block.type === 'tool_result' ? { ...block, content: [{ text: shot.note, type: 'text' }, image(shot.url)] } : block;
		});
		after = at;
		// the image went with its note
		index += 1;
	}

	return [...folded, ...rest];
};

// a Chat Completions image (a data URL, as the editor sends every image, or a link) as Claude's image block
const image = (url: string): Anthropic.ImageBlockParam => {
	const [, type, data] = DATA_URL.exec(url) ?? [];
	const mediaType = MEDIA_TYPES.find(item => {
		return item === type;
	});

	if (!mediaType || !data) {
		return { source: { type: 'url', url }, type: 'image' };
	}

	return { source: { data, media_type: mediaType, type: 'base64' }, type: 'image' };
};

// a user message's content as Claude's blocks: its words and its images
const parts = (content: ChatMessage['content']): Anthropic.ContentBlockParam[] => {
	if (typeof content === 'string') {
		return [{ text: content, type: 'text' }];
	}

	return (content ?? []).map((part): Anthropic.ContentBlockParam => {
		return part.type === 'text' ? { text: part.text, type: 'text' } : image(part.image_url.url);
	});
};

// a message's words: its text, or its text parts joined
const text = (content: ChatMessage['content']) => {
	if (typeof content === 'string') {
		return content;
	}

	return (content ?? [])
		.map(part => {
			return part.type === 'text' ? part.text : '';
		})
		.join('');
};

// The editor's conversation as Claude's: the system message apart; each assistant message as its content
// (`assistantContent`), left out when it has none; a turn's tool messages as one user message of tool_result blocks; and
// the user message after them folded into those (`fold`)
const toAnthropic = (messages: ChatMessage[]) => {
	let converted: Anthropic.MessageParam[] = [];
	let system = '';

	for (const message of messages) {
		const last = converted.at(-1);
		const results = last?.role === 'user' && Array.isArray(last.content) && last.content[0]?.type === 'tool_result' ? last.content : null;
		const kept = results ? converted.slice(0, -1) : converted;

		if (message.role === 'system') {
			system = system ? `${system}\n\n${text(message.content)}` : text(message.content);
		} else if (message.role === 'assistant') {
			const content = assistantContent(message);

			converted = content ? [...converted, { content, role: 'assistant' }] : converted;
		} else if (message.role === 'tool') {
			const result: Anthropic.ToolResultBlockParam = { content: text(message.content), tool_use_id: message.tool_call_id ?? '', type: 'tool_result' };

			converted = [...kept, { content: [...(results ?? []), result], role: 'user' }];
		} else {
			converted = [...kept, { content: results ? fold({ content: message.content, results }) : parts(message.content), role: 'user' }];
		}
	}

	return { messages: converted, system };
};

// Claude's answer as the editor's message: its words, its tool calls in Chat Completions' shape (each tool_use's input as
// JSON), and Claude's content itself, stashed on it (`claudeContent`) for the next round to send back as it came
const toChatMessage = (content: Anthropic.ContentBlock[]): ChatMessage => {
	const calls = content.flatMap((block): ChatToolCall[] => {
		return block.type === 'tool_use' ? [{ function: { arguments: JSON.stringify(block.input), name: block.name }, id: block.id, type: 'function' }] : [];
	});
	const words = content
		.flatMap(block => {
			return block.type === 'text' ? [block.text] : [];
		})
		.join('\n\n');
	const message: ChatMessage = { claudeContent: content, content: words || null, role: 'assistant' };

	if (calls.length) {
		message.tool_calls = calls;
	}

	return message;
};

// a tool call's arguments as the input Claude takes back: {} where they are no JSON
const toolInput = (args: string): unknown => {
	try {
		return JSON.parse(args);
	} catch {
		return {};
	}
};

export type { Model };
export { MAX_TOKENS, PRICES };
export default { chooseCommands, cost };
```

### OpenAI

The Responses API: in the prototype, OpenAI's newer models refused an image beside tools through Chat Completions. Each screenshot goes into the `function_call_output` it answers. It needs the `openai` package and `OPENAI_API_KEY`.

* `store: false`: OpenAI keeps no copy, and the conversation is the editor's. `include: ['reasoning.encrypted_content']` has the reasoning come back encrypted, so OpenAI's items, that reasoning among them, ride on the message and go back as they came.
* `strict: false` on each tool: the editor's schemas leave optional fields out of `required`, which OpenAI's strict mode refuses.
* The cache is OpenAI's own, on with no setting: the conversation only grows, so each round starts as the round before.

```ts openai.ts theme={"dark"}
import OpenAI from 'openai';
import { toResponseInputItems } from 'openai/lib/responses/ResponseInputItems';

import type { ChatContentPart, ChatMessage, ChatTool, ChatToolCall } from '@embededitor/full/react';

// The editor's onAiChooseCommands on OpenAI's Responses API, for the site's server, where the key stays (OPENAI_API_KEY): each round
// the editor sends its conversation, in Chat Completions' shape, and `chooseCommands` sends it to OpenAI as Responses' input items,
// then gives the answer back in the editor's shape. OpenAI's own items ride along on the message it gives back, and go
// back as they came, so its reasoning stays valid. Nothing is stored at OpenAI (`store: false`): the conversation is the
// editor's, and the reasoning comes back encrypted for the next round to send. OpenAI caches on its own: the conversation
// only grows, so each round starts as the round before

// how a round's input reads, the item type the Responses API takes
type Item = OpenAI.Responses.ResponseInputItem;

// the most a round may write
const MAX_OUTPUT_TOKENS = 16000;

// an assistant message as OpenAI's items: what OpenAI gave it, stashed on it by `chooseCommands` (its reasoning included), or else
// its words and tool calls; none for one with neither, which OpenAI takes no turn for
const assistantItems = (message: ChatMessage): Item[] => {
	const calls = message.tool_calls ?? [];
	const words = text(message.content);

	if (!words && !calls.length) {
		return [];
	}

	if (Array.isArray(message.openaiItems)) {
		return message.openaiItems;
	}

	const uses = calls.map((call): Item => {
		return { arguments: call.function.arguments, call_id: call.id, name: call.function.name, type: 'function_call' };
	});

	return words ? [{ content: words, role: 'assistant' }, ...uses] : uses;
};

// One round of the editor's conversation on `model`: OpenAI's answer as the editor's next message, and what the round
// used. `signal` aborts the call when the person stops. An answer OpenAI stopped short of (a refusal, or one cut at
// `max_output_tokens` with a tool call perhaps cut off) rejects: the editor then says Couldn’t Complete the Request and keeps what
// the rounds before did. The client is made here, so a server whose environment exists per request has its key
const chooseCommands = async ({ messages, model, signal, tools }: { messages: ChatMessage[]; model: string; signal: AbortSignal; tools: ChatTool[] }) => {
	const client = new OpenAI({ maxRetries: 4 });
	const native = toResponses(messages);
	const res = await client.responses.create(
		{
			// with nothing stored, the reasoning comes back encrypted, for the next round to send back
			include: ['reasoning.encrypted_content'],
			input: native.input,
			instructions: native.instructions,
			max_output_tokens: MAX_OUTPUT_TOKENS,
			model,
			store: false,
			// the editor's schemas leave optional fields out of `required`, which OpenAI's strict mode refuses
			tools: tools.map(({ function: { description, name, parameters } }) => {
				return { description, name, parameters, strict: false, type: 'function' };
			})
		},
		{ signal }
	);

	if (res.status !== 'completed') {
		throw new Error(`OpenAI stopped: ${res.incomplete_details?.reason ?? res.status}`);
	}

	const refused = res.output.some(item => {
		return (
			item.type === 'message' &&
			item.content.some(part => {
				return part.type === 'refusal';
			})
		);
	});

	if (refused) {
		throw new Error('OpenAI stopped: refusal');
	}

	return { message: toChatMessage(res.output), usage: res.usage ?? null };
};

// the user message the editor sends after a turn's tool messages, folded into their function_call_output items (the
// run of them at the end of `input`): each screenshot (an image right after its note) into the next output whose
// content is that note, and anything else, as the words of a request that follows a stopped turn, after them as a user
// message
const fold = ({ content, input }: { content: ChatMessage['content']; input: Item[] }): Item[] => {
	const list: ChatContentPart[] = typeof content === 'string' ? [{ text: content, type: 'text' }] : (content ?? []);
	// the turn's outputs are the ones after the last item that is none
	let after = input.findLastIndex(item => {
		return item.type !== 'function_call_output';
	});
	let folded = input;
	let rest: ChatContentPart[] = [];

	for (let index = 0; index < list.length; index += 1) {
		const part = list[index];
		const next = list[index + 1];
		const shot = part.type === 'text' && next?.type === 'image_url' ? { note: part.text, url: next.image_url.url } : null;
		const at = shot
			? folded.findIndex((item, itemIndex) => {
					return itemIndex > after && item.type === 'function_call_output' && item.output === shot.note;
				})
			: -1;

		if (!shot || at === -1) {
			rest = [...rest, part];
			continue;
		}

		const output: OpenAI.Responses.ResponseFunctionCallOutputItemList = [
			{ text: shot.note, type: 'input_text' },
			{ detail: 'high', image_url: shot.url, type: 'input_image' }
		];

		folded = folded.map((item, itemIndex) => {
			return itemIndex === at && item.type === 'function_call_output' ? { ...item, output } : item;
		});
		after = at;
		// the image went with its note
		index += 1;
	}

	return rest.length ? [...folded, { content: parts(rest), role: 'user' }] : folded;
};

// a user message's content as OpenAI's parts: its words and its images (a data URL, as the editor sends every image)
const parts = (content: ChatMessage['content']): OpenAI.Responses.ResponseInputMessageContentList => {
	if (typeof content === 'string') {
		return [{ text: content, type: 'input_text' }];
	}

	return (content ?? []).map((part): OpenAI.Responses.ResponseInputContent => {
		return part.type === 'text' ? { text: part.text, type: 'input_text' } : { detail: 'high', image_url: part.image_url.url, type: 'input_image' };
	});
};

// a message's words: its text, or its text parts joined
const text = (content: ChatMessage['content']) => {
	if (typeof content === 'string') {
		return content;
	}

	return (content ?? [])
		.map(part => {
			return part.type === 'text' ? part.text : '';
		})
		.join('');
};

// OpenAI's answer as the editor's message: its words, its tool calls in Chat Completions' shape, and OpenAI's items
// themselves, stashed on it (`openaiItems`) for the next round to send back as they came
const toChatMessage = (output: OpenAI.Responses.ResponseOutputItem[]): ChatMessage => {
	const calls = output.flatMap((item): ChatToolCall[] => {
		return item.type === 'function_call' ? [{ function: { arguments: item.arguments, name: item.name }, id: item.call_id, type: 'function' }] : [];
	});
	const words = output
		.flatMap(item => {
			if (item.type !== 'message') {
				return [];
			}

			return item.content.flatMap(part => {
				return part.type === 'output_text' ? [part.text] : [];
			});
		})
		.join('\n\n');
	const message: ChatMessage = { content: words || null, openaiItems: toResponseInputItems(output), role: 'assistant' };

	if (calls.length) {
		message.tool_calls = calls;
	}

	return message;
};

// The editor's conversation as OpenAI's: the system message apart, as the instructions; each assistant message as its
// items (`assistantItems`), none when it has neither words nor tool calls; each tool message as a function_call_output;
// and the user message after a turn's tool messages folded into those (`fold`)
const toResponses = (messages: ChatMessage[]) => {
	let input: Item[] = [];
	let instructions = '';

	for (const message of messages) {
		if (message.role === 'system') {
			instructions = instructions ? `${instructions}\n\n${text(message.content)}` : text(message.content);
		} else if (message.role === 'assistant') {
			input = [...input, ...assistantItems(message)];
		} else if (message.role === 'tool') {
			input = [...input, { call_id: message.tool_call_id ?? '', output: text(message.content), type: 'function_call_output' }];
		} else {
			input = fold({ content: message.content, input });
		}
	}

	return { input, instructions };
};

export default { chooseCommands };
```

### Gemini

Chat Completions, through Google's OpenAI-compatible endpoint, with the `openai` package and `GEMINI_API_KEY`. The editor's messages go as they are, but for an empty assistant turn.

* **The screenshot can't go inside the tool's answer.** A `tool` message takes text alone in Chat Completions, so each screenshot stays in the user message after the turn's tool messages, where the editor puts it.
* **The thought signatures go back.** Gemini 3 signs its tool calls and needs the signatures back on the next rounds; Google's OpenAI compatibility carries them in Chat Completions. The server keeps each tool call whole, as Gemini gave it, and the editor sends it back as it came.
* **The cache is implicit,** on with no setting in Gemini 2.5 and later.
* Google calls its OpenAI compatibility a beta.

```ts gemini.ts theme={"dark"}
import OpenAI from 'openai';

import type { ChatMessage, ChatTool, ChatToolCall } from '@embededitor/full/react';

// The editor's onAiChooseCommands on Gemini, through Google's OpenAI-compatible Chat Completions endpoint, for the site's server,
// where the key stays (GEMINI_API_KEY): the editor's conversation is already in that shape, so `chooseCommands` sends it as it is,
// but for an assistant message with neither words nor tool calls, which Gemini takes no turn for. Each tool call goes
// back as Gemini gave it, so the thought signature Gemini 3 needs back on later rounds goes with it. Gemini caches on its
// own (implicit caching, Gemini 2.5 and later): the conversation only grows, so each round starts as the round before

// Google's OpenAI-compatible endpoint
const BASE_URL = 'https://generativelanguage.googleapis.com/v1beta/openai/';

// One round of the editor's conversation on `model`: Gemini's answer as the editor's next message, and what the round
// used. `signal` aborts the call when the person stops. An answer Gemini stopped short of (blocked, or cut at its output
// limit with a tool call perhaps cut off) rejects: the editor then says Couldn’t Complete the Request and keeps what the rounds
// before did. The client is made here, so a server whose environment exists per request has its key
const chooseCommands = async ({ messages, model, signal, tools }: { messages: ChatMessage[]; model: string; signal: AbortSignal; tools: ChatTool[] }) => {
	const client = new OpenAI({ apiKey: process.env.GEMINI_API_KEY, baseURL: BASE_URL, maxRetries: 4 });
	const res = await client.chat.completions.create({ messages: toCompletions(messages), model, tools }, { signal });
	const [choice] = res.choices;

	if (!choice || choice.finish_reason === 'content_filter' || choice.finish_reason === 'length') {
		throw new Error(`Gemini stopped: ${choice ? choice.finish_reason : 'no answer'}`);
	}

	return { message: toChatMessage(choice.message), usage: res.usage ?? null };
};

// a message's words: its text, or its text parts joined
const text = (content: ChatMessage['content']) => {
	if (typeof content === 'string') {
		return content;
	}

	return (content ?? [])
		.map(part => {
			return part.type === 'text' ? part.text : '';
		})
		.join('');
};

// Gemini's answer as the editor's message: its words and its tool calls, each call kept whole, with whatever Gemini put
// on it (its thought signature among it)
const toChatMessage = ({ content, tool_calls }: OpenAI.ChatCompletionMessage): ChatMessage => {
	const calls = (tool_calls ?? []).flatMap((call): ChatToolCall[] => {
		return call.type === 'function' ? [{ ...call }] : [];
	});
	const message: ChatMessage = { content, role: 'assistant' };

	if (calls.length) {
		message.tool_calls = calls;
	}

	return message;
};

// The editor's conversation as Chat Completions takes it: each message as it is, its tool calls whole, an assistant
// message with neither words nor tool calls left out. The screenshots stay in the user message after a turn's tool
// messages, where the editor puts them: a tool message takes no image in Chat Completions
const toCompletions = (messages: ChatMessage[]) => {
	return messages.flatMap((message): OpenAI.ChatCompletionMessageParam[] => {
		const words = text(message.content);

		if (message.role === 'system') {
			return [{ content: words, role: 'system' }];
		}

		if (message.role === 'tool') {
			return [{ content: words, role: 'tool', tool_call_id: message.tool_call_id ?? '' }];
		}

		if (message.role === 'user') {
			const content = typeof message.content === 'string' ? message.content : (message.content ?? []);

			return [{ content, role: 'user' }];
		}

		if (!words && !message.tool_calls?.length) {
			return [];
		}

		return [message.tool_calls?.length ? { content: words || null, role: 'assistant', tool_calls: message.tool_calls } : { content: words, role: 'assistant' }];
	});
};

export default { chooseCommands };
```

The OpenAI and Gemini servers follow each provider's documentation of November 2026. The prototype measured neither with the editor's guide.


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