curl --request POST \
--url https://api.apiyi.com/v1/images/edits \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: multipart/form-data' \
--form model=MAI-Image-2.6-Flash \
--form 'prompt=Change the teapot to a deep cobalt blue glaze, keep everything else identical' \
--form image='@example-file' \
--form image2='@example-file'import requests
url = "https://api.apiyi.com/v1/images/edits"
files = {
"image": ("example-file", open("example-file", "rb")),
"image2": ("example-file", open("example-file", "rb"))
}
payload = {
"model": "MAI-Image-2.6-Flash",
"prompt": "Change the teapot to a deep cobalt blue glaze, keep everything else identical"
}
headers = {"Authorization": "Bearer <token>"}
response = requests.post(url, data=payload, files=files, headers=headers)
print(response.text)const form = new FormData();
form.append('model', 'MAI-Image-2.6-Flash');
form.append('prompt', 'Change the teapot to a deep cobalt blue glaze, keep everything else identical');
form.append('image', '<string>');
form.append('image2', '{
"fileName": "example-file"
}');
const options = {method: 'POST', headers: {Authorization: 'Bearer <token>'}};
options.body = form;
fetch('https://api.apiyi.com/v1/images/edits', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.apiyi.com/v1/images/edits",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"model\"\r\n\r\nMAI-Image-2.6-Flash\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"prompt\"\r\n\r\nChange the teapot to a deep cobalt blue glaze, keep everything else identical\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"image\"; filename=\"example-file\"\r\nContent-Type: application/octet-stream\r\n\r\n<string>\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"image2\"; filename=\"example-file\"\r\nContent-Type: application/octet-stream\r\n\r\n{\r\n \"fileName\": \"example-file\"\r\n}\r\n-----011000010111000001101001--",
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>",
"Content-Type: multipart/form-data"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "https://api.apiyi.com/v1/images/edits"
payload := strings.NewReader("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"model\"\r\n\r\nMAI-Image-2.6-Flash\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"prompt\"\r\n\r\nChange the teapot to a deep cobalt blue glaze, keep everything else identical\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"image\"; filename=\"example-file\"\r\nContent-Type: application/octet-stream\r\n\r\n<string>\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"image2\"; filename=\"example-file\"\r\nContent-Type: application/octet-stream\r\n\r\n{\r\n \"fileName\": \"example-file\"\r\n}\r\n-----011000010111000001101001--")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("Authorization", "Bearer <token>")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("https://api.apiyi.com/v1/images/edits")
.header("Authorization", "Bearer <token>")
.body("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"model\"\r\n\r\nMAI-Image-2.6-Flash\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"prompt\"\r\n\r\nChange the teapot to a deep cobalt blue glaze, keep everything else identical\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"image\"; filename=\"example-file\"\r\nContent-Type: application/octet-stream\r\n\r\n<string>\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"image2\"; filename=\"example-file\"\r\nContent-Type: application/octet-stream\r\n\r\n{\r\n \"fileName\": \"example-file\"\r\n}\r\n-----011000010111000001101001--")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.apiyi.com/v1/images/edits")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request.body = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"model\"\r\n\r\nMAI-Image-2.6-Flash\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"prompt\"\r\n\r\nChange the teapot to a deep cobalt blue glaze, keep everything else identical\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"image\"; filename=\"example-file\"\r\nContent-Type: application/octet-stream\r\n\r\n<string>\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"image2\"; filename=\"example-file\"\r\nContent-Type: application/octet-stream\r\n\r\n{\r\n \"fileName\": \"example-file\"\r\n}\r\n-----011000010111000001101001--"
response = http.request(request)
puts response.read_body{
"created": 1791000788,
"data": [
{
"b64_json": "<string>"
}
],
"usage": {
"prompt_tokens": 1000,
"total_tokens": 1000
}
}Справочник по API редактирования изображений
Справочник по API редактирования изображений MAI-Image 2.6 с интерактивным Playground — загрузка эталонного изображения с инструкцией, слияние двух изображений через image + image2, загрузка файлов только через multipart/form-data
curl --request POST \
--url https://api.apiyi.com/v1/images/edits \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: multipart/form-data' \
--form model=MAI-Image-2.6-Flash \
--form 'prompt=Change the teapot to a deep cobalt blue glaze, keep everything else identical' \
--form image='@example-file' \
--form image2='@example-file'import requests
url = "https://api.apiyi.com/v1/images/edits"
files = {
"image": ("example-file", open("example-file", "rb")),
"image2": ("example-file", open("example-file", "rb"))
}
payload = {
"model": "MAI-Image-2.6-Flash",
"prompt": "Change the teapot to a deep cobalt blue glaze, keep everything else identical"
}
headers = {"Authorization": "Bearer <token>"}
response = requests.post(url, data=payload, files=files, headers=headers)
print(response.text)const form = new FormData();
form.append('model', 'MAI-Image-2.6-Flash');
form.append('prompt', 'Change the teapot to a deep cobalt blue glaze, keep everything else identical');
form.append('image', '<string>');
form.append('image2', '{
"fileName": "example-file"
}');
const options = {method: 'POST', headers: {Authorization: 'Bearer <token>'}};
options.body = form;
fetch('https://api.apiyi.com/v1/images/edits', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.apiyi.com/v1/images/edits",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"model\"\r\n\r\nMAI-Image-2.6-Flash\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"prompt\"\r\n\r\nChange the teapot to a deep cobalt blue glaze, keep everything else identical\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"image\"; filename=\"example-file\"\r\nContent-Type: application/octet-stream\r\n\r\n<string>\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"image2\"; filename=\"example-file\"\r\nContent-Type: application/octet-stream\r\n\r\n{\r\n \"fileName\": \"example-file\"\r\n}\r\n-----011000010111000001101001--",
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>",
"Content-Type: multipart/form-data"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "https://api.apiyi.com/v1/images/edits"
payload := strings.NewReader("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"model\"\r\n\r\nMAI-Image-2.6-Flash\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"prompt\"\r\n\r\nChange the teapot to a deep cobalt blue glaze, keep everything else identical\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"image\"; filename=\"example-file\"\r\nContent-Type: application/octet-stream\r\n\r\n<string>\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"image2\"; filename=\"example-file\"\r\nContent-Type: application/octet-stream\r\n\r\n{\r\n \"fileName\": \"example-file\"\r\n}\r\n-----011000010111000001101001--")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("Authorization", "Bearer <token>")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("https://api.apiyi.com/v1/images/edits")
.header("Authorization", "Bearer <token>")
.body("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"model\"\r\n\r\nMAI-Image-2.6-Flash\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"prompt\"\r\n\r\nChange the teapot to a deep cobalt blue glaze, keep everything else identical\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"image\"; filename=\"example-file\"\r\nContent-Type: application/octet-stream\r\n\r\n<string>\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"image2\"; filename=\"example-file\"\r\nContent-Type: application/octet-stream\r\n\r\n{\r\n \"fileName\": \"example-file\"\r\n}\r\n-----011000010111000001101001--")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.apiyi.com/v1/images/edits")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request.body = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"model\"\r\n\r\nMAI-Image-2.6-Flash\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"prompt\"\r\n\r\nChange the teapot to a deep cobalt blue glaze, keep everything else identical\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"image\"; filename=\"example-file\"\r\nContent-Type: application/octet-stream\r\n\r\n<string>\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"image2\"; filename=\"example-file\"\r\nContent-Type: application/octet-stream\r\n\r\n{\r\n \"fileName\": \"example-file\"\r\n}\r\n-----011000010111000001101001--"
response = http.request(request)
puts response.read_body{
"created": 1791000788,
"data": [
{
"b64_json": "<string>"
}
],
"usage": {
"prompt_tokens": 1000,
"total_tokens": 1000
}
}Bearer sk-xxx), выберите файл image, заполните prompt и model и отправьте запрос.multipart/form-dataОтправка JSON на /v1/images/edits (с image в виде URL, data URI или чистого base64) возвращает 400:request Content-Type isn't multipart/form-data
image + image2, а не image[]При использовании двух референсных изображений назовите первое поле image, а второе — image2. Повторение image[], повторение image или добавление поля mask вернут ошибку 400 File must be attached in a form field with a name starting with 'image'.Это означает, что отправка нескольких изображений через OpenAI SDK с помощью client.images.edit(image=[f1, f2]) не работает (он отправляет image[]). Редактирование одного изображения через SDK работает корректно.response_format, seed или negative_prompt (400). Ответ всегда data[0].b64_json (PNG).Примеры кода
Python (OpenAI SDK · одно изображение)
from openai import OpenAI
import base64
client = OpenAI(
api_key="sk-your-api-key",
base_url="https://api.apiyi.com/v1",
timeout=180.0
)
# images.edit uses a multipart file upload under the hood; do not pass response_format
resp = client.images.edit(
model="MAI-Image-2.6-Flash",
image=open("teaset.jpg", "rb"),
prompt="Change the teapot to a deep cobalt blue glaze, keep everything else identical"
)
with open("edited.png", "wb") as f:
f.write(base64.b64decode(resp.data[0].b64_json))
Python (requests · одно изображение)
import base64
import os
import requests
# Pass the file via files=; requests sets multipart/form-data and the boundary for you
# Do not use json=, and do not set Content-Type by hand
with open("teaset.jpg", "rb") as fp:
response = requests.post(
"https://api.apiyi.com/v1/images/edits",
headers={"Authorization": f"Bearer {os.environ['APIYI_API_KEY']}"},
data={
"model": "MAI-Image-2.6",
"prompt": "Change the teapot to a deep cobalt blue glaze, keep everything else exactly the same"
},
files={"image": ("teaset.jpg", fp, "image/jpeg")},
timeout=180
)
response.raise_for_status()
with open("edited.png", "wb") as f:
f.write(base64.b64decode(response.json()["data"][0]["b64_json"]))
Python (слияние двух изображений · image + image2)
import base64
import os
import requests
files = {
"image": ("scene.jpg", open("scene.jpg", "rb"), "image/jpeg"), # image 1
"image2": ("person.jpg", open("person.jpg", "rb"), "image/jpeg"), # image 2: field name is image2
}
response = requests.post(
"https://api.apiyi.com/v1/images/edits",
headers={"Authorization": f"Bearer {os.environ['APIYI_API_KEY']}"},
data={
"model": "MAI-Image-2.6",
"prompt": "Have the person from image 2 sit at the table in image 1, arranging the tea set, natural light, photorealistic"
},
files=files,
timeout=180
)
response.raise_for_status()
with open("fused.png", "wb") as f:
f.write(base64.b64decode(response.json()["data"][0]["b64_json"]))
cURL
# Single-image edit: -F means multipart/form-data, @ uploads a local file
curl -X POST "https://api.apiyi.com/v1/images/edits" \
-H "Authorization: Bearer sk-your-api-key" \
-F "model=MAI-Image-2.6-Flash" \
-F "prompt=Change the teapot to a deep cobalt blue glaze, keep everything else identical" \
-F "[email protected]" \
| python3 -c "import sys,json,base64; open('edited.png','wb').write(base64.b64decode(json.load(sys.stdin)['data'][0]['b64_json']))"
# Two-image fusion with the canvas changed to 1536×1024
curl -X POST "https://api.apiyi.com/v1/images/edits" \
-H "Authorization: Bearer sk-your-api-key" \
-F "model=MAI-Image-2.6" \
-F "prompt=Have the person from image 2 sit at the table in image 1, arranging the tea set" \
-F "width=1536" \
-F "height=1024" \
-F "[email protected]" \
-F "[email protected]"
Node.js (fetch + FormData)
import fs from 'node:fs';
const form = new FormData();
form.append('model', 'MAI-Image-2.6-Flash');
form.append('prompt', 'Replace the background with a snowy pine forest at night, keep the person unchanged');
form.append('image', new Blob([fs.readFileSync('./photo.jpg')]), 'photo.jpg');
// Second reference image: form.append('image2', ...)
const resp = await fetch('https://api.apiyi.com/v1/images/edits', {
method: 'POST',
// Do not set Content-Type by hand; FormData adds the boundary
headers: { 'Authorization': `Bearer ${process.env.APIYI_API_KEY}` },
body: form,
signal: AbortSignal.timeout(120000)
});
const data = await resp.json();
fs.writeFileSync('edited.png', Buffer.from(data.data[0].b64_json, 'base64'));
Справочник параметров
| Параметр | Тип | Обязательный | По умолчанию | Описание |
|---|---|---|---|---|
model | string | ✅ | — | MAI-Image-2.6 ($0.12/изображение) или MAI-Image-2.6-Flash ($0.06/изображение), с учётом регистра |
prompt | string | ✅ | — | Инструкция по редактированию. Укажите, что нужно изменить, а что должно остаться без изменений |
image | file | ✅ | — | Файл референсного изображения (первое) |
image2 | file | ❌ | — | Второе референсное изображение (для объединения двух изображений) |
width / height | integer | ❌ | По пропорциям оригинала | Размер на выходе, те же правила, что и для text-to-image; другое соотношение сторон меняет композицию изображения |
n | integer | ❌ | 1 | Количество изображений. Работает на этом эндпоинте, тарифицируется за каждое изображение |
mask | — | — | — | Не поддерживается; возвращает 400 |
response_formatseednegative_prompt | — | — | — | Возвращают 400 |
width / height.Результаты редактирования и составление prompt
Эндпоинт редактирования сохраняет композицию, цвета и детали оригинала и изменяет только то, что указано в prompt:
| Prompt | Результат |
|---|---|
✅ Change the teapot to a deep cobalt blue glaze, keep everything else exactly the same | Меняется только цвет чайника; надписи и другие объекты остаются попиксельно идентичными |
✅ Turn this photo into a watercolor painting, keep the composition | Стиль перерисован, композиция сохранена |
✅ Have the person from image 2 sit at the table in image 1 | Слияние двух изображений: изображение 1 задает сцену, изображение 2 — человека |
⚠️ Make it look better | Слишком неконкретно; масштаб изменений непредсказуем |
image / image2 как на «image 1 / image 2» в prompt. В наших тестах сохранение сходства людей лишь умеренное (черты лица могут смещаться), поэтому сначала проверьте работу на небольшой выборке, если важно портретное сходство.Формат ответа
{
"created": 1791000788,
"data": [
{
"b64_json": "iVBORw0KGgoAAAANSUhEUgAABAAAAAQACAIAAADwf7zU..."
}
],
"usage": {
"prompt_tokens": 1000,
"total_tokens": 1000,
"input_tokens": 1000,
"output_tokens": 0
}
}
b64_json— это обычный base64 без префиксаdata:, который декодируется в PNG.- При
n > 1массивdataсодержит несколько элементов; не считывайте толькоdata[0]. urlиrevised_promptне возвращаются.
usage: он содержит плейсхолдеры (prompt_tokens всегда равен 1000 × количество изображений). Редактирование стоит столько же, сколько text-to-image, и тарифицируется за каждое изображение; определяющим является счет в консоли APIYI.Авторизации
API key from the APIYI console
Тело
Model ID (case-sensitive)
MAI-Image-2.6-Flash, MAI-Image-2.6 Edit instruction. State what to change and that everything else stays the same
"Change the teapot to a deep cobalt blue glaze, keep everything else identical"
Reference image file (the first one, "image 1" in the prompt). png / jpg / webp
Optional second reference image ("image 2" in the prompt), for two-image fusion
Optional output width. Same rules as text-to-image: each side ≥ 768, width × height ≤ 2,359,296, sent together with height
x >= 768Optional output height, same rules as width
x >= 768Number of images. Works on this endpoint, billed per image
x >= 11
Была ли эта страница полезной?