Skip to content
Merged
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
3 changes: 2 additions & 1 deletion cm-skills/cm-imagegen/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ CodexManager config policy:
- An explicitly configured but unset `env_key` is a configuration error; do not substitute another provider's key. Never use ChatGPT login tokens as platform keys, and do not modify `auth.json` or ask the user to switch authentication modes to use this skill.
- Use `CODEXMANAGER_IMAGE_MODEL` only for the image model override; otherwise use `gpt-image-2` for OpenAI-compatible Images providers, or `image-01` when the provider base URL targets the image_generation API (`minimax.io` / `minimaxi.com` hosts).
- Use the CLI's configured image model by default. Do not copy a different default from the official imagegen CLI, infer that Images API is unavailable from a text-only model list, or interpret a single `model_not_found` response as proof that the provider supports no image models. Report the actual endpoint/model error and check the configured image model.
- When the provider base URL targets the image_generation API, the CLI calls `POST /v1/image_generation` with `aspect_ratio`/`width`/`height`/`seed`/`n`/`prompt_optimizer`/`response_format` request fields, passes `--image` inputs as `subject_reference`, and parses `data.image_urls` / `data.image_base64` + `base_resp.status_code`; otherwise it calls the OpenAI Images `/images/generations` and `/images/edits` endpoints and parses `data[].b64_json`.
- For `MiniMax-H3-Image` or `MiniMax-H3-Image-Highspeed`, use `generate` with the regional `/v1` base URL. The CLI calls `/images/generations` and reports saved images and per-image errors. See `references/image-api.md`.
- For other models, when the provider base URL targets the image_generation API, the CLI calls `POST /v1/image_generation` with `aspect_ratio`/`width`/`height`/`seed`/`n`/`prompt_optimizer`/`response_format` request fields, passes `--image` inputs as `subject_reference`, and parses `data.image_urls` / `data.image_base64` + `base_resp.status_code`; otherwise it calls the OpenAI Images `/images/generations` and `/images/edits` endpoints and parses `data[].b64_json`.
- Use `CODEXMANAGER_IMAGE_OUTPUT_DIR` only for the output directory override; otherwise save under the current working directory's `generated-images/` folder.

Save-path policy:
Expand Down
5 changes: 3 additions & 2 deletions cm-skills/cm-imagegen/references/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,9 @@ Use `python3` on systems where that is the installed interpreter name.
## Defaults and options

- Model: `gpt-image-2` for OpenAI-compatible Images endpoints; `image-01` for MiniMax endpoints. `--model` takes precedence over `CODEXMANAGER_IMAGE_MODEL`.
- Size: `1024x1024`; use `--size` to override.
- Response format: `b64_json`. The OpenAI-compatible path saves `data[].b64_json`; URL responses are not saved by that path. MiniMax supports `url` and `base64` and converts `b64_json` to `base64`.
- Select `MiniMax-H3-Image` or `MiniMax-H3-Image-Highspeed` for H3 text-to-image. See [the H3 API reference](image-api.md#minimax-h3-text-to-image) for H3 size and response defaults.
- Size: H3 selects the dimensions when omitted. The standard Images endpoint defaults to `1024x1024`.
- Response format: `b64_json`. The OpenAI-compatible path saves `data[].b64_json`; URL responses are not saved by that path. The legacy MiniMax endpoint supports `url` and `base64` and converts `b64_json` to `base64`.
- Output directory: `generated-images/` under the current working directory, overridden by `CODEXMANAGER_IMAGE_OUTPUT_DIR` or `--out-dir`.
- Filename: generated automatically, overridden by `--filename`. Existing paths receive a timestamp suffix.
- Timeout: 600 seconds, overridden by `--timeout`.
Expand Down
15 changes: 13 additions & 2 deletions cm-skills/cm-imagegen/references/image-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,20 @@ For edits the CLI sends JSON `images: [{"image_url": "data:image/...;base64,..."

The OpenAI-compatible CLI path saves `data[].b64_json` and reports absolute file paths. It does not save URL-only responses. Image option support and limits depend on the gateway and selected upstream model; check the actual error before retrying with different options.

## MiniMax image generation API
## MiniMax H3 text-to-image

When the provider base URL targets `minimax.io` or `minimaxi.com`, the CLI uses `POST <provider.base_url>/image_generation` for generate and edit. The default model is `image-01`.
Select `MiniMax-H3-Image` or `MiniMax-H3-Image-Highspeed` with `generate --model` or `CODEXMANAGER_IMAGE_MODEL`.
Use the base URL for the credential region, `https://api.minimax.io/v1` or `https://api.minimax.cn/v1`.
The CLI sends one POST to `<provider.base_url>/images/generations` with a timeout of at least 600 seconds.

- Set `--size WIDTHxHEIGHT` or `--aspect-ratio X:Y`. Omitting both lets H3 choose the dimensions.
- Set `--n` from 1 to 10. Use `--output-format` for the encoded file format.
- The default `--response-format b64_json` saves inline images. With `--response-format url`, the CLI downloads each successful image.
- For a mixed response, `paths` contains the saved images and `errors` lists each failed item's zero-based index and provider error. The CLI includes the `request_id` for troubleshooting.

## Legacy MiniMax image generation API

For other models, when the provider base URL targets `minimax.io` or `minimaxi.com`, the CLI uses `POST <provider.base_url>/image_generation` for generate and edit. The default model is `image-01`.

Request fields:

Expand Down
93 changes: 75 additions & 18 deletions cm-skills/cm-imagegen/scripts/cm_image_gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
DEFAULT_SIZE = "1024x1024"
DEFAULT_RESPONSE_FORMAT = "b64_json"
DEFAULT_MINIMAX_MODEL = "image-01"
H3_MODELS = {"MiniMax-H3-Image", "MiniMax-H3-Image-Highspeed"}
MINIMAX_HOST_FRAGMENTS = ("minimax.io", "minimaxi.com")


Expand Down Expand Up @@ -294,14 +295,58 @@ def parse_minimax_response(data: dict, out_dir: Path, filename: str | None, time
return paths


def h3_payload(args: argparse.Namespace, model: str) -> dict:
for option in ("width", "height", "seed", "quality", "background"):
if getattr(args, option) is not None:
raise SystemExit(f"--{option} is not supported for H3 generation.")
if args.n is not None and not 1 <= args.n <= 10:
raise SystemExit("--n must be between 1 and 10 for H3 generation.")
if args.aspect_ratio and args.size not in (None, "auto"):
raise SystemExit("Use either an explicit --size or --aspect-ratio for H3 generation.")
payload = {
"model": model,
"prompt": args.prompt,
"response_format": "b64_json" if args.response_format == "base64" else args.response_format,
}
for option in ("size", "aspect_ratio", "n", "output_format"):
value = getattr(args, option)
if value is not None:
payload[option] = value
if args.prompt_optimizer is False and args.size in (None, "auto") and args.aspect_ratio in (None, "auto"):
raise SystemExit("--prompt-optimizer false requires an explicit --size or --aspect-ratio for H3.")
if args.prompt_optimizer is not None:
payload["disable_prompt_enhanced"] = not args.prompt_optimizer
return payload


def save_h3_images(items: list, out_dir: Path, filename: str | None, timeout: int) -> tuple[list[Path], list[dict]]:
paths = []
errors = []
for index, item in enumerate(items):
if not isinstance(item, dict):
raise SystemExit(f"Invalid H3 result at index {index}.")
if error := item.get("error"):
errors.append({"index": index, "error": error})
elif url := item.get("url"):
if not isinstance(url, str) or not url.startswith(("https://", "http://")):
raise SystemExit(f"Invalid image URL in H3 result {index}.")
paths.append(save_image_bytes(download_bytes(url, timeout), out_dir, filename, index))
else:
paths.append(save_image_from_item(item, out_dir, filename, index))
if not paths:
raise SystemExit(f"H3 generation failed: {json.dumps(errors, ensure_ascii=False)}")
return paths, errors


def generate(args: argparse.Namespace) -> int:
base_url = provider_base_url()
api_key = load_api_key()
minimax = is_minimax_base_url(base_url)
model = args.model or os.environ.get("CODEXMANAGER_IMAGE_MODEL") or (
DEFAULT_MINIMAX_MODEL if minimax else DEFAULT_MODEL
)
if minimax:
h3 = model in H3_MODELS
if minimax and not h3:
url = f"{base_url.rstrip('/')}/image_generation"
payload = minimax_payload(args, model, args.prompt)
data = request_json(url, api_key, payload, args.timeout)
Expand All @@ -318,26 +363,34 @@ def generate(args: argparse.Namespace) -> int:
print(json.dumps(result, ensure_ascii=False, indent=2))
return 0
url = f"{base_url.rstrip('/')}/images/generations"
payload = {
"model": model,
"prompt": args.prompt,
"size": args.size,
"response_format": args.response_format,
}
if args.n is not None:
payload["n"] = args.n
if args.quality:
payload["quality"] = args.quality
if args.background:
payload["background"] = args.background
if args.output_format:
payload["output_format"] = args.output_format
data = request_json(url, api_key, payload, args.timeout)
if h3:
payload = h3_payload(args, model)
timeout = max(args.timeout, 600)
else:
payload = {
"model": model,
"prompt": args.prompt,
"size": args.size or DEFAULT_SIZE,
"response_format": args.response_format,
}
if args.n is not None:
payload["n"] = args.n
if args.quality:
payload["quality"] = args.quality
if args.background:
payload["background"] = args.background
if args.output_format:
payload["output_format"] = args.output_format
timeout = args.timeout
data = request_json(url, api_key, payload, timeout)
items = data.get("data")
if not isinstance(items, list) or not items:
raise SystemExit(f"Images API returned no data items: {json.dumps(data, ensure_ascii=False)[:1000]}")
out_dir = Path(args.out_dir) if args.out_dir else output_dir()
paths = [save_image_from_item(item, out_dir, args.filename, index) for index, item in enumerate(items)]
if h3:
paths, errors = save_h3_images(items, out_dir, args.filename, timeout)
else:
paths = [save_image_from_item(item, out_dir, args.filename, index) for index, item in enumerate(items)]
result = {
"ok": True,
"base_url": base_url,
Expand All @@ -346,6 +399,8 @@ def generate(args: argparse.Namespace) -> int:
"usage": data.get("usage"),
"created": data.get("created"),
}
if h3:
result.update(request_id=data.get("request_id"), errors=errors)
print(json.dumps(result, ensure_ascii=False, indent=2))
return 0

Expand All @@ -357,6 +412,8 @@ def edit(args: argparse.Namespace) -> int:
model = args.model or os.environ.get("CODEXMANAGER_IMAGE_MODEL") or (
DEFAULT_MINIMAX_MODEL if minimax else DEFAULT_MODEL
)
if model in H3_MODELS:
raise SystemExit("H3 text-to-image models support the generate command only.")
image_paths = [Path(value).expanduser() for value in args.image]
if minimax:
url = f"{base_url.rstrip('/')}/image_generation"
Expand Down Expand Up @@ -443,7 +500,7 @@ def main() -> int:
gen = sub.add_parser("generate")
gen.add_argument("--prompt", required=True)
gen.add_argument("--model")
gen.add_argument("--size", default=DEFAULT_SIZE)
gen.add_argument("--size")
gen.add_argument("--response-format", default=DEFAULT_RESPONSE_FORMAT, choices=["b64_json", "url", "base64"])
gen.add_argument("--out-dir")
gen.add_argument("--filename")
Expand Down
92 changes: 92 additions & 0 deletions cm-skills/cm-imagegen/tests/test_cm_image_gen.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import base64
import importlib.util
import io
import json
import os
import subprocess
import sys
import tempfile
import threading
import unittest
import urllib.error
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from unittest.mock import patch
Expand Down Expand Up @@ -201,5 +203,95 @@ def log_message(self, *args):
thread.join(timeout=5)


class H3GenerationTests(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.root = Path(temp.name)
self.base_url = "https://api.minimax.io/v1"
self.model = "MiniMax-H3-Image"

def run_cli(self, *args):
argv = ["cm_image_gen.py", *args, "--prompt", "a plum blossom", "--out-dir", str(self.root)]
env = {"CODEXMANAGER_IMAGE_BASE_URL": self.base_url, "CODEXMANAGER_IMAGE_MODEL": self.model}
with patch.dict(os.environ, env, clear=True), patch.object(sys, "argv", argv), \
patch.object(imagegen, "load_api_key", return_value="fixture"), \
patch("sys.stdout", new_callable=io.StringIO) as stdout:
self.assertEqual(imagegen.main(), 0)
return json.loads(stdout.getvalue())

def test_models_use_regional_endpoint_and_save_inline_output(self):
for region, model in (("io", "MiniMax-H3-Image"), ("cn", "MiniMax-H3-Image-Highspeed")):
with self.subTest(region=region):
self.base_url = f"https://api.minimax.{region}/v1"
self.model = model
data = {"data": [{"b64_json": base64.b64encode(PNG_BYTES).decode()}], "request_id": "r1"}
with patch("urllib.request.urlopen", return_value=io.BytesIO(json.dumps(data).encode())) as http:
result = self.run_cli("generate", "--size", "1024x1024", "--timeout", "30")
http.assert_called_once()
req = http.call_args.args[0]
self.assertEqual((req.method, req.full_url), ("POST", self.base_url + "/images/generations"))
self.assertEqual(req.get_header("Authorization"), "Bearer fixture")
self.assertEqual(http.call_args.kwargs["timeout"], 600)
self.assertEqual(json.loads(req.data), {"model": model, "prompt": "a plum blossom",
"response_format": "b64_json", "size": "1024x1024"})
self.assertEqual(Path(result["paths"][0]).read_bytes(), PNG_BYTES)
self.assertEqual(result["request_id"], "r1")
self.assertEqual(result["errors"], [])

def test_partial_success_downloads_url_and_reports_failed_item(self):
error = {"code": "1027", "message": "image failed the content safety check"}
image_url = "https://cdn.example/image.png"
data = {"data": [{"error": error}, {"url": image_url}], "usage": {"generated_images": 1}}
with patch("urllib.request.urlopen", side_effect=[io.BytesIO(json.dumps(data).encode()),
io.BytesIO(PNG_BYTES)]) as http:
result = self.run_cli("generate", "--n", "2", "--response-format", "url",
"--aspect-ratio", "3:2", "--output-format", "png", "--prompt-optimizer", "false")
post, download = http.call_args_list
payload = json.loads(post.args[0].data)
self.assertEqual(payload, {"model": self.model, "prompt": "a plum blossom", "response_format": "url",
"n": 2, "aspect_ratio": "3:2", "output_format": "png", "disable_prompt_enhanced": True})
self.assertEqual(download.args[0].full_url, image_url)
self.assertIsNone(download.args[0].get_header("Authorization"))
self.assertEqual(Path(result["paths"][0]).read_bytes(), PNG_BYTES)
self.assertEqual(result["errors"], [{"index": 0, "error": error}])
self.assertEqual(result["usage"], data["usage"])

def test_http_failure_is_reported_without_resubmission(self):
data = b'{"type":"error","error":{"type":"server_error","message":"internal error (1000)"}}'
error = urllib.error.HTTPError(self.base_url, 500, "Server Error", {}, io.BytesIO(data))
with patch("urllib.request.urlopen", side_effect=error) as http:
with self.assertRaisesRegex(SystemExit, r"HTTP 500.*internal error"):
self.run_cli("generate")
http.assert_called_once()

def test_item_errors_without_images_fail(self):
data = {"data": [{"error": {"code": "1027", "message": "rejected image"}}]}
with patch("urllib.request.urlopen", return_value=io.BytesIO(json.dumps(data).encode())) as http:
with self.assertRaisesRegex(SystemExit, "rejected image"):
self.run_cli("generate")
http.assert_called_once()

def test_edit_and_conflicting_size_fail_before_submission(self):
with patch("urllib.request.urlopen") as http:
with self.assertRaisesRegex(SystemExit, "generate command only"):
self.run_cli("edit", "--image", "unused.png")
with self.assertRaisesRegex(SystemExit, "explicit --size"):
self.run_cli("generate", "--size", "1024x1024", "--aspect-ratio", "1:1")
with self.assertRaisesRegex(SystemExit, "requires an explicit"):
self.run_cli("generate", "--prompt-optimizer", "false")
http.assert_not_called()

def test_existing_minimax_generation_uses_legacy_response(self):
self.model = "image-01"
data = {"base_resp": {"status_code": 0}, "data": {"image_base64": [base64.b64encode(PNG_BYTES).decode()]}}
with patch("urllib.request.urlopen", return_value=io.BytesIO(json.dumps(data).encode())) as http:
result = self.run_cli("generate")
req = http.call_args.args[0]
self.assertEqual(req.full_url, self.base_url + "/image_generation")
self.assertEqual(json.loads(req.data)["response_format"], "base64")
self.assertEqual(Path(result["paths"][0]).read_bytes(), PNG_BYTES)


if __name__ == "__main__":
unittest.main()
Loading