diff --git a/docs/modules/image_tools.md b/docs/modules/image_tools.md index 2fe292f7..d4f03847 100644 --- a/docs/modules/image_tools.md +++ b/docs/modules/image_tools.md @@ -40,6 +40,24 @@ from evoagentx.tools import ( ## Toolkits and Tools +### MiniMaxImageToolkit + +Set `MINIMAX_API_KEY` or pass `api_key` to the toolkit. Select `region="cn"` +for a mainland China key. The default region is `"global"`. + +```python +from evoagentx.tools import MiniMaxImageToolkit + +generate = MiniMaxImageToolkit().get_tool("minimax_image_generation") +result = generate(prompt="A fox walking across a snowy field") +``` + +The default model is `MiniMax-H3-Image`. Set `model="MiniMax-H3-Image-Highspeed"` +to use the faster variant. `n` accepts 1–10 images and `size` accepts `auto` +or `WIDTHxHEIGHT`. Download successful URLs from `results` before they expire. +A partially successful batch also includes indexed entries in `errors`. +Request failures return `error`. Retrying a request can incur a second charge. + ### OpenAIImageToolkit - Tools included: diff --git a/evoagentx/tools/__init__.py b/evoagentx/tools/__init__.py index 2a688dce..ff2c59eb 100644 --- a/evoagentx/tools/__init__.py +++ b/evoagentx/tools/__init__.py @@ -19,6 +19,7 @@ from .storage_file import StorageToolkit from .image_tools.flux_image_tools.image_generation_edit import FluxImageGenerationEditTool from .image_tools.flux_image_tools.toolkit import FluxImageGenerationToolkit +from .image_tools.minimax_image_tools.toolkit import MiniMaxImageToolkit from .image_tools.openai_image_tools.toolkit import OpenAIImageToolkit from .image_tools.openrouter_image_tools.image_analysis import ImageAnalysisTool as OpenRouterImageAnalysisTool from .image_tools.openrouter_image_tools.image_generation import OpenRouterImageGenerationEditTool @@ -60,6 +61,7 @@ "StorageToolkit", "FluxImageGenerationEditTool", "FluxImageGenerationToolkit", + "MiniMaxImageToolkit", "OpenAIImageToolkit", "OpenRouterImageAnalysisTool", "OpenRouterImageGenerationEditTool", diff --git a/evoagentx/tools/image_tools/minimax_image_tools/image_generation.py b/evoagentx/tools/image_tools/minimax_image_tools/image_generation.py new file mode 100644 index 00000000..2a03289d --- /dev/null +++ b/evoagentx/tools/image_tools/minimax_image_tools/image_generation.py @@ -0,0 +1,95 @@ +"""MiniMax H3 text-to-image generation.""" + +import os + +import requests +from pydantic import PrivateAttr + +from ...tool import Tool + +_ENDPOINTS = { + "global": "https://api.minimax.io/v1/images/generations", + "cn": "https://api.minimax.cn/v1/images/generations", +} +_MODELS = ("MiniMax-H3-Image", "MiniMax-H3-Image-Highspeed") + + +class MiniMaxImageGenerationTool(Tool): + """Generate images with H3 and return their temporary URLs.""" + + name: str = "minimax_image_generation" + description: str = "Generate images from a text prompt using MiniMax H3." + inputs: dict[str, dict[str, str]] = { # noqa: RUF012 - Tool validates the schema at class creation. + "prompt": {"type": "string", "description": "Text describing the image."}, + "model": { + "type": "string", + "description": "MiniMax-H3-Image or MiniMax-H3-Image-Highspeed.", + }, + "size": {"type": "string", "description": "Image size: auto or WIDTHxHEIGHT."}, + "n": {"type": "integer", "description": "Number of images, from 1 to 10."}, + } + required: list[str] = ["prompt"] # noqa: RUF012 - Tool validates this field at class creation. + _api_key: str = PrivateAttr() + _endpoint: str = PrivateAttr() + + def __init__(self, api_key: str | None = None, region: str = "global"): + """Configure the regional endpoint and read the key from MINIMAX_API_KEY if omitted.""" + super().__init__() + if region not in _ENDPOINTS: + raise ValueError("MiniMax region must be 'global' or 'cn'.") + self._endpoint = _ENDPOINTS[region] + self._api_key = api_key or os.getenv("MINIMAX_API_KEY") + if not self._api_key: + raise ValueError("Provide a MiniMax API key or set MINIMAX_API_KEY.") + + def __call__( + self, + prompt: str, + model: str = "MiniMax-H3-Image", + size: str = "auto", + n: int = 1, + ): + """Return successful image URLs and any per-image errors, or a request error.""" + if model not in _MODELS or not 1 <= n <= 10 or not prompt.strip(): + return { + "error": "Provide a nonempty prompt, a supported H3 model and n between 1 and 10." + } + try: + # A second POST would generate and charge for another batch of images. + response = requests.post( + self._endpoint, + headers={"Authorization": f"Bearer {self._api_key}"}, + json={ + "model": model, + "prompt": prompt, + "n": n, + "size": size, + "response_format": "url", + }, + timeout=600, + allow_redirects=False, + ) + if not 200 <= response.status_code < 300: + try: + message = response.json()["error"]["message"] + except (KeyError, TypeError, ValueError): + message = response.reason + return { + "error": f"MiniMax returned HTTP {response.status_code}: {message}" + } + items = response.json()["data"] + if not isinstance(items, list) or not items: + return {"error": "MiniMax returned no image results."} + urls, errors = [], [] + for index, item in enumerate(items): + if not isinstance(item, dict): + errors.append({"index": index, "message": "Invalid image result."}) + elif isinstance(item.get("error"), dict): + errors.append({"index": index, **item["error"]}) + elif isinstance(item.get("url"), str) and item["url"]: + urls.append(item["url"]) + else: + errors.append({"index": index, "message": "Missing image URL."}) + return {"results": urls, "count": len(urls), "errors": errors} + except (requests.RequestException, KeyError, TypeError, ValueError) as exc: + return {"error": f"MiniMax image generation failed: {exc}"} diff --git a/evoagentx/tools/image_tools/minimax_image_tools/toolkit.py b/evoagentx/tools/image_tools/minimax_image_tools/toolkit.py new file mode 100644 index 00000000..8d37870f --- /dev/null +++ b/evoagentx/tools/image_tools/minimax_image_tools/toolkit.py @@ -0,0 +1,20 @@ +"""Expose H3 image generation through the EvoAgentX toolkit interface.""" + +from ...tool import Toolkit +from .image_generation import MiniMaxImageGenerationTool + + +class MiniMaxImageToolkit(Toolkit): + """Provide the MiniMax text-to-image tool.""" + + def __init__( + self, + api_key: str | None = None, + region: str = "global", + name: str = "MiniMaxImageToolkit", + ): + """Select the credential and its region for image generation.""" + super().__init__( + name=name, + tools=[MiniMaxImageGenerationTool(api_key=api_key, region=region)], + ) diff --git a/tests/src/tools/test_minimax_image_generation.py b/tests/src/tools/test_minimax_image_generation.py new file mode 100644 index 00000000..14d6d4e1 --- /dev/null +++ b/tests/src/tools/test_minimax_image_generation.py @@ -0,0 +1,88 @@ +"""Exercise MiniMax image generation through the public toolkit.""" + +from unittest.mock import Mock, patch + +import pytest +import requests + +from evoagentx.tools import MiniMaxImageToolkit + + +@pytest.mark.parametrize( + "region,tld,model", + [ + ("global", "io", "MiniMax-H3-Image"), + ("cn", "cn", "MiniMax-H3-Image-Highspeed"), + ], +) +def test_image_generation_preserves_partial_success(region, tld, model): + """Check the regional request and expose successful and failed items.""" + tool = MiniMaxImageToolkit(api_key="example", region=region).get_tool( + "minimax_image_generation" + ) + error = {"code": "1027", "message": "Image failed the content safety check"} + data = [ + {"url": "https://example.com/image.jpg", "size": "1024x1024"}, + {"error": error}, + ] + response = Mock(status_code=200) + response.json.return_value = {"data": data, "request_id": "request-id"} + with patch("requests.post", return_value=response) as post: + result = tool(prompt="A snowy field", model=model, size="1024x1024", n=2) + post.assert_called_once_with( + f"https://api.minimax.{tld}/v1/images/generations", + headers={"Authorization": "Bearer example"}, + json={ + "model": model, + "prompt": "A snowy field", + "size": "1024x1024", + "n": 2, + "response_format": "url", + }, + timeout=600, + allow_redirects=False, + ) + assert result == { + "results": [data[0]["url"]], + "count": 1, + "errors": [{"index": 1, **error}], + } + + +def test_generation_reports_request_error_without_retry(monkeypatch): + """Surface the provider message and leave non-idempotent retries to the caller.""" + monkeypatch.setenv("MINIMAX_API_KEY", "example") + tool = MiniMaxImageToolkit().get_tool("minimax_image_generation") + response = Mock(status_code=429) + response.json.return_value = { + "error": {"type": "rate_limit_error", "message": "Rate limited (1002)"} + } + with patch("requests.post", return_value=response) as post: + assert tool(prompt="A fox") == { + "error": "MiniMax returned HTTP 429: Rate limited (1002)" + } + assert post.call_count == 1 + with patch("requests.post", side_effect=requests.Timeout("read timed out")) as post: + assert "read timed out" in tool(prompt="A fox")["error"] + assert post.call_count == 1 + + +def test_generation_returns_default_model_image(): + """A prompt alone returns an image URL using the standard H3 model.""" + toolkit = MiniMaxImageToolkit(api_key="example") + tool = toolkit.get_tool("minimax_image_generation") + assert toolkit.get_tool_schemas()[0]["function"]["parameters"]["required"] == [ + "prompt" + ] + image_url = "https://example.com/generated.jpg" + response = Mock(status_code=200) + response.json.return_value = { + "data": [{"url": image_url, "revised_prompt": "A fox in sunlight"}] + } + with patch("requests.post", return_value=response) as post: + assert tool(prompt="A fox") == { + "results": [image_url], + "count": 1, + "errors": [], + } + assert post.call_args.kwargs["json"]["model"] == "MiniMax-H3-Image"