Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ GOOGLE_API_KEY=
GOOGLE_GENAI_USE_VERTEXAI=false
#GOOGLE_CLOUD_PROJECT=
MINIMAX_PLAN_API_KEY=
# Regional API for H3 image generation: global or cn.
MINIMAX_IMAGE_REGION=global
MIMO_PLAN_API_KEY=

# OpenAI Compatible Provider
Expand Down
1 change: 1 addition & 0 deletions intentkit/config/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@ def __init__(self) -> None:
self.deepseek_api_key: str | None = self.load("DEEPSEEK_API_KEY")
self.xai_api_key: str | None = self.load("XAI_API_KEY")
self.minimax_plan_api_key: str | None = self.load("MINIMAX_PLAN_API_KEY")
self.minimax_image_region: str = self.load("MINIMAX_IMAGE_REGION", "global")
self.mimo_plan_api_key: str | None = self.load("MIMO_PLAN_API_KEY")
self.openrouter_api_key: str | None = self.load("OPENROUTER_API_KEY")
# OpenAI Compatible provider
Expand Down
8 changes: 7 additions & 1 deletion intentkit/tools/image/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@
)
from intentkit.tools.image.gpt import GPTImageFlagship, GPTImageMini
from intentkit.tools.image.grok import GrokImage
from intentkit.tools.image.minimax import MiniMaxImage
from intentkit.tools.image.minimax import (
MiniMaxH3Image,
MiniMaxH3ImageHighspeed,
MiniMaxImage,
)
from intentkit.tools.image.openrouter import FluxPro, Riverflow
from intentkit.tools.meta import ToolsetMeta

Expand All @@ -36,6 +40,8 @@
"image_flux_pro": FluxPro,
"image_riverflow": Riverflow,
"image_minimax": MiniMaxImage,
"image_minimax_h3": MiniMaxH3Image,
"image_minimax_h3_highspeed": MiniMaxH3ImageHighspeed,
}


Expand Down
82 changes: 82 additions & 0 deletions intentkit/tools/image/minimax.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
"""MiniMax image generation tools."""

import base64
import binascii
import logging
from decimal import Decimal
from typing import override

import httpx
from langchain_core.tools import ArgsSchema
from langchain_core.tools.base import ToolException
from pydantic import BaseModel, ConfigDict, Field

from intentkit.config.config import config
from intentkit.tools.image.base import ImageBaseTool
Expand Down Expand Up @@ -92,3 +95,82 @@ class MiniMaxImage(MiniMaxImageBase):
)
price: Decimal = Decimal("30")
native_model: str = "image-01"


class MiniMaxH3Input(BaseModel):
"""Arguments for H3 text-to-image generation."""

model_config = ConfigDict(extra="forbid")
prompt: str = Field(description="Text description of the image to generate")


class MiniMaxH3Image(MiniMaxImageBase):
"""Generate one image through the regional MiniMax H3 generations API."""

name: str = "image_minimax_h3"
title: str = "MiniMax H3 Image"
description: str = "Generate an image from a text prompt using MiniMax H3 Image."
native_model: str = "MiniMax-H3-Image"
args_schema: ArgsSchema | None = MiniMaxH3Input
price: Decimal = Decimal("30")

@override
async def _generate_native(self, prompt: str, images: list[bytes] | None) -> bytes:
if images:
raise ToolException(
"MiniMax H3 image generation only accepts text prompts."
)
base_url = {"global": _MINIMAX_BASE_URL, "cn": "https://api.minimax.cn/v1"}.get(
config.minimax_image_region
)
if not base_url:
raise ToolException("MINIMAX_IMAGE_REGION must be global or cn.")

# A generation can take ten minutes. Retrying after a disconnect can bill twice.
async with httpx.AsyncClient(timeout=610) as client:
response = await client.post(
f"{base_url}/images/generations",
headers={"Authorization": f"Bearer {config.minimax_plan_api_key}"},
json={
"model": self.native_model,
"prompt": prompt,
"response_format": "b64_json",
},
)
response.raise_for_status()
payload = response.json()
entries = payload.get("data") if isinstance(payload, dict) else None
if (
not isinstance(entries, list)
or not entries
or not isinstance(entries[0], dict)
):
raise ToolException("MiniMax H3 response contained no image.")
item = entries[
0
] # n defaults to one, matching ImageBaseTool's single attachment.
error = item.get("error")
if isinstance(error, dict):
raise ToolException(
f"MiniMax H3 image generation failed: {error.get('message', 'Unknown error')}"
)
encoded = item.get("b64_json")
if not isinstance(encoded, str) or not encoded:
raise ToolException("MiniMax H3 response contained no image.")
try:
return base64.b64decode(encoded, validate=True)
except (binascii.Error, ValueError) as exc:
raise ToolException(
"MiniMax H3 response contained invalid base64 image data."
) from exc


class MiniMaxH3ImageHighspeed(MiniMaxH3Image):
"""Highspeed variant of the MiniMax H3 text-to-image tool."""

name: str = "image_minimax_h3_highspeed"
title: str = "MiniMax H3 Image Highspeed"
description: str = (
"Generate an image from a text prompt using MiniMax H3 Image Highspeed."
)
native_model: str = "MiniMax-H3-Image-Highspeed"
77 changes: 77 additions & 0 deletions tests/tools/test_image.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
"""Tests for image generation tools."""

import base64
import json
from decimal import Decimal
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch

import httpx
import pytest
from langchain_core.tools.base import ToolException
from pydantic import ValidationError

from intentkit.tools.image import available, get_tools
Expand All @@ -17,6 +20,7 @@
)
from intentkit.tools.image.gpt import GPTImageFlagship, GPTImageMini
from intentkit.tools.image.grok import GrokImage
from intentkit.tools.image.minimax import MiniMaxH3Image, MiniMaxH3Input
from intentkit.tools.image.openrouter import FluxPro, Riverflow


Expand Down Expand Up @@ -242,3 +246,76 @@ async def test_openrouter_gpt_image_empty_response_raises():
):
with pytest.raises(ToolException, match="No image found"):
await GPTImageFlagship()._generate_via_openrouter("a cat", None)


@pytest.mark.asyncio
@pytest.mark.parametrize(
("name", "region", "host", "model"),
[
("image_minimax_h3", "global", "api.minimax.io", "MiniMax-H3-Image"),
(
"image_minimax_h3_highspeed",
"cn",
"api.minimax.cn",
"MiniMax-H3-Image-Highspeed",
),
],
)
async def test_minimax_h3_generation(name: str, region: str, host: str, model: str):
tool, legacy = await get_tools([name, "image_minimax"])
assert legacy.native_model == "image-01"
assert tool.args_schema is MiniMaxH3Input
with pytest.raises(ValidationError):
MiniMaxH3Input.model_validate({"prompt": "draw a cat", "images": ["reference"]})

def respond(request: httpx.Request) -> httpx.Response:
assert str(request.url) == f"https://{host}/v1/images/generations"
assert request.method == "POST"
assert request.headers["authorization"] == "Bearer test"
assert json.loads(request.content) == {
"model": model,
"prompt": "draw a cat",
"response_format": "b64_json",
}
return httpx.Response(200, json={"data": [{"b64_json": "aW1hZ2U="}]})

client = httpx.AsyncClient(transport=httpx.MockTransport(respond))
with (
patch(
"intentkit.tools.image.minimax.config",
minimax_image_region=region,
minimax_plan_api_key="test",
),
patch(
"intentkit.tools.image.minimax.httpx.AsyncClient", return_value=client
) as make_client,
):
assert await tool._generate_native("draw a cat", None) == b"image"
assert make_client.call_args.kwargs["timeout"] >= 600


@pytest.mark.asyncio
@pytest.mark.parametrize(
("data", "message"),
[
([{"error": {"code": "1027", "message": "image blocked"}}], "image blocked"),
([{"b64_json": "invalid!"}], "invalid base64"),
([], "contained no image"),
],
)
async def test_minimax_h3_rejects_failed_image(data: list, message: str):
client = httpx.AsyncClient(
transport=httpx.MockTransport(
lambda _: httpx.Response(200, json={"data": data})
)
)
with (
patch(
"intentkit.tools.image.minimax.config",
minimax_image_region="cn",
minimax_plan_api_key="test",
),
patch("intentkit.tools.image.minimax.httpx.AsyncClient", return_value=client),
pytest.raises(ToolException, match=message),
):
await MiniMaxH3Image()._generate_native("draw a cat", None)