feat(image): support MiniMax H3 image models (#6671)

Co-authored-by: sseepsse <5190941+sseepsse@users.noreply.github.com>
This commit is contained in:
chengyongruandsseepsse authored and GitHub committed 2026-11-15 19:54:18 +08:00
1 parent 2c669935a5
commit 96eb1ace6f
3 files changed
+158 -3

No files matched your search

+6 -2
View File
@@ -222,7 +222,11 @@ Configure:
### MiniMax
MiniMax `image-01` supports text-to-image and reference-image (subject reference) edits. Supported aspect ratios are `1:1`, `16:9`, `4:3`, `3:2`, `2:3`, `3:4`, `9:16`, and `21:9`.
MiniMax supports text-to-image and reference-image edits with `MiniMax-H3-Image` and `MiniMax-H3-Image-Highspeed`. Set the image size to `1K`, `2K`, `4K`, or an explicit size such as `2720x1536`. Explicit sizes take precedence over the aspect ratio. H3 accepts up to 16 reference images. See [MiniMax's image generation documentation](https://platform.minimax.io/docs/guides/image-generation) for size limits and pricing.
A timed-out or interrupted H3 request may still complete and be billed. Retrying starts another billable generation.
The legacy `image-01` model remains available, with aspect ratios `1:1`, `16:9`, `4:3`, `3:2`, `2:3`, `3:4`, `9:16`, and `21:9`.
<details>
<summary>Manual configuration</summary>
@@ -238,7 +242,7 @@ MiniMax `image-01` supports text-to-image and reference-image (subject reference
"imageGeneration": {
"enabled": true,
"provider": "minimax",
"model": "image-01",
"model": "MiniMax-H3-Image",
"defaultAspectRatio": "1:1"
}
}
+79 -1
View File
@@ -967,7 +967,7 @@ class MiniMaxImageGenerationClient(ImageGenerationProvider):
"""Async client for MiniMax image generation API."""
provider_name = "minimax"
model_options = ("image-01",)
model_options = ("image-01", "MiniMax-H3-Image", "MiniMax-H3-Image-Highspeed")
missing_key_message = (
"MiniMax API key is not configured. Set providers.minimax.apiKey."
)
@@ -993,6 +993,9 @@ class MiniMaxImageGenerationClient(ImageGenerationProvider):
if not self.api_key:
raise ImageGenerationError(self.missing_key_message)
if model in ("MiniMax-H3-Image", "MiniMax-H3-Image-Highspeed"):
return await self._generate_h3(prompt, model, reference_images, aspect_ratio, image_size)
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json",
@@ -1019,6 +1022,52 @@ class MiniMaxImageGenerationClient(ImageGenerationProvider):
return await self._generate_with_client(body, headers)
async def _generate_h3(
self, prompt: str, model: str, reference_images: list[str] | None,
aspect_ratio: str | None, image_size: str | None,
) -> GeneratedImageResponse:
refs = reference_images or []
if len(refs) > 16:
raise ImageGenerationError("MiniMax H3 accepts at most 16 reference images")
body: dict[str, Any] = {"model": model, "prompt": prompt, "response_format": "b64_json"}
if image_size and image_size not in {"1K", "2K", "4K"}:
body["size"] = image_size
else:
if aspect_ratio:
body["aspect_ratio"] = aspect_ratio
if image_size:
body["area"] = image_size
if refs:
body["images"] = [{"image_url": image_path_to_data_url(path)} for path in refs]
body.update(self.extra_body)
body = {key: value for key, value in body.items() if value is not None}
_validate_minimax_h3_body(body)
headers = {"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json", **self.extra_headers}
endpoint = "edits" if refs else "generations"
try:
if self._client is not None:
response = await self._http_post(f"{self.api_base}/images/{endpoint}", headers=headers, body=body)
else:
client_kwargs = self._http_client_kwargs()
client_kwargs["timeout"] = max(self.timeout, 660.0)
async with httpx.AsyncClient(**client_kwargs) as client:
response = await self._http_post(f"{self.api_base}/images/{endpoint}", headers=headers, body=body, client=client)
response.raise_for_status()
except httpx.TimeoutException as exc:
raise ImageGenerationError("MiniMax H3 timed out; generation may still complete and be billed") from exc
except httpx.HTTPStatusError as exc:
raise ImageGenerationError(f"MiniMax H3 image generation failed: {exc.response.text[:500]}") from exc
except httpx.RequestError as exc:
raise ImageGenerationError(f"MiniMax H3 request failed; generation may still be billed: {exc}") from exc
payload = response.json()
images = await _openai_images_from_payload(payload, proxy=self.proxy)
if not images:
errors = [item["error"] for item in _as_json_objects(payload.get("data")) if item.get("error")]
if errors:
raise ImageGenerationError(f"MiniMax H3 returned no images: {errors}")
self._require_images(images, payload)
return GeneratedImageResponse(images=images, content="", raw=payload)
async def _generate_with_client(
self,
body: dict[str, Any],
@@ -1046,6 +1095,35 @@ class MiniMaxImageGenerationClient(ImageGenerationProvider):
return GeneratedImageResponse(images=images, content="", raw=payload)
def _validate_minimax_h3_body(body: dict[str, Any]) -> None:
if body.get("stream"):
raise ImageGenerationError("MiniMax H3 streaming is not supported")
if body.get("n", 1) != 1:
raise ImageGenerationError("MiniMax H3 generates one image per request; use the tool's count parameter")
size = body.get("size")
if size and size != "auto":
match = re.fullmatch(r"(\d+)x(\d+)", str(size))
if not match:
raise ImageGenerationError("MiniMax H3 size must be WIDTHxHEIGHT or auto")
width, height = map(int, match.groups())
if not height or not 655_360 <= width * height <= 20_000_000 or not height <= 3 * width <= 9 * height:
raise ImageGenerationError("MiniMax H3 size is outside the supported area or aspect ratio")
if "aspect_ratio" in body or "area" in body:
raise ImageGenerationError("MiniMax H3 explicit size cannot be combined with aspect_ratio or area")
ratio = body.get("aspect_ratio")
if ratio and ratio != "auto":
match = re.fullmatch(r"(\d+):(\d+)", str(ratio))
if not match:
raise ImageGenerationError("MiniMax H3 aspect ratio must be X:Y")
width, height = map(int, match.groups())
if not (1 <= width <= 300 and 1 <= height <= 300 and height <= 3 * width <= 9 * height):
raise ImageGenerationError("MiniMax H3 aspect ratio is outside the supported range")
if body.get("area") not in (None, "1K", "2K", "4K"):
raise ImageGenerationError("MiniMax H3 area must be 1K, 2K, or 4K")
if body.get("disable_prompt_enhanced") and (not size or size == "auto") and (not ratio or ratio == "auto"):
raise ImageGenerationError("MiniMax H3 requires size or aspect ratio when prompt enhancement is disabled")
def _minimax_images_from_payload(payload: dict[str, Any]) -> list[str]:
images: list[str] = []
data = payload.get("data")
+73
View File
@@ -1681,3 +1681,76 @@ def test_image_provider_http_client_kwargs_include_explicit_proxy() -> None:
"proxy": proxy,
"trust_env": False,
}
@pytest.mark.asyncio
async def test_minimax_h3_generation_and_edit(tmp_path: Path) -> None:
fake = FakeClient(FakeResponse({"data": [{"b64_json": RAW_B64}]}))
client = MiniMaxImageGenerationClient(api_key="test", client=fake) # type: ignore[arg-type]
result = await client.generate(prompt="draw", model="MiniMax-H3-Image", aspect_ratio="16:9", image_size="2K")
assert result.images == [PNG_DATA_URL]
assert fake.calls[-1]["url"].endswith("/v1/images/generations")
assert fake.calls[-1]["json"] == {
"model": "MiniMax-H3-Image", "prompt": "draw", "response_format": "b64_json",
"aspect_ratio": "16:9", "area": "2K",
}
ref = tmp_path / "ref.png"
ref.write_bytes(PNG_BYTES)
await client.generate(prompt="edit", model="MiniMax-H3-Image-Highspeed", reference_images=[str(ref)],
aspect_ratio="1:1", image_size="2720x1536")
body = fake.calls[-1]["json"]
assert fake.calls[-1]["url"].endswith("/v1/images/edits")
assert body["size"] == "2720x1536"
assert "area" not in body and "aspect_ratio" not in body
assert body["images"] == [{"image_url": "data:image/png;base64," + base64.b64encode(PNG_BYTES).decode("ascii")}]
@pytest.mark.asyncio
@pytest.mark.parametrize("size,ratio", [("100x100", "1:1"), ("2K", "4:1"), ("3K", "1:1")])
async def test_minimax_h3_invalid_sizes_fail_before_request(size: str, ratio: str) -> None:
fake = FakeClient(FakeResponse({}))
client = MiniMaxImageGenerationClient(api_key="test", client=fake) # type: ignore[arg-type]
with pytest.raises(ImageGenerationError):
await client.generate(prompt="draw", model="MiniMax-H3-Image", image_size=size, aspect_ratio=ratio)
assert not fake.calls
@pytest.mark.asyncio
async def test_minimax_h3_partial_response_and_url_download(generated_image_downloads) -> None:
fake = FakeClient(FakeResponse({"data": [{"error": {"message": "failed"}}, {"url": "https://example.com/image.png"}]}))
client = MiniMaxImageGenerationClient(api_key="test", client=fake, proxy="http://proxy") # type: ignore[arg-type]
result = await client.generate(prompt="draw", model="MiniMax-H3-Image")
assert result.images == [PNG_DATA_URL]
assert generated_image_downloads == [("https://example.com/image.png", "http://proxy")]
@pytest.mark.asyncio
async def test_minimax_h3_timeout_warns_about_billing() -> None:
class TimeoutClient:
async def post(self, url: str, **kwargs: Any) -> None:
raise httpx.ReadTimeout("timeout")
client = MiniMaxImageGenerationClient(api_key="test", client=TimeoutClient()) # type: ignore[arg-type]
with pytest.raises(ImageGenerationError, match="may still complete and be billed"):
await client.generate(prompt="draw", model="MiniMax-H3-Image")
@pytest.mark.asyncio
async def test_minimax_h3_client_timeout_and_no_retry(monkeypatch) -> None:
calls: list[httpx.Request] = []
timeouts: list[float] = []
original_client = httpx.AsyncClient
def handler(request: httpx.Request) -> httpx.Response:
calls.append(request)
raise httpx.ReadTimeout("timeout", request=request)
def make_client(**kwargs: Any) -> httpx.AsyncClient:
timeouts.append(kwargs["timeout"])
return original_client(transport=httpx.MockTransport(handler), **kwargs)
monkeypatch.setattr("nanobot.providers.image_generation.httpx.AsyncClient", make_client)
client = MiniMaxImageGenerationClient(api_key="test")
with pytest.raises(ImageGenerationError, match="billed"):
await client.generate(prompt="draw", model="MiniMax-H3-Image")
assert timeouts == [660.0]
assert len(calls) == 1