diff --git a/docs/guide/skills-and-tools.md b/docs/guide/skills-and-tools.md index ddbe46889b..e18dd2afe4 100644 --- a/docs/guide/skills-and-tools.md +++ b/docs/guide/skills-and-tools.md @@ -188,9 +188,12 @@ validated or converted, and provider-specific format restrictions still apply. The [image-generation skill](../../skills/public/image-generation/SKILL.md#output-handling) decodes Gemini base64 image data before opening the output file, -preserving an existing image when decoding fails. With the legacy MiniMax -`/v1/image_generation` endpoint, a decode failure can still erase an existing -output image. Use a fresh `--output-file` path to keep the previous image. +preserving an existing image when decoding fails. For OpenAI-compatible providers, +the CLI rejects an empty download or empty data URL before creating the output +directory or opening the file. If a MiniMax prompt exceeds 1500 characters, the CLI +reports the limit on stderr and exits with status 1 before contacting the provider. +With the legacy MiniMax `/v1/image_generation` endpoint, a decode failure can still +erase an existing output image. Use a fresh `--output-file` path to keep the previous image. The [music-generation skill](../../skills/public/music-generation/SKILL.md#output-handling) preserves existing output when the provider returns malformed, empty or unrecognized audio. @@ -305,7 +308,9 @@ The built-in `image-generation` skill supports Gemini, MiniMax, and OpenAI-compatible Images APIs. Select the latter with `IMAGE_GENERATION_PROVIDER=openai`, then configure `IMAGE_GENERATION_API_KEY`, `IMAGE_GENERATION_BASE_URL`, and -`IMAGE_GENERATION_MODEL`. Run the skill's script in an isolated sandbox such as +`IMAGE_GENERATION_MODEL`. If the explicitly selected provider's API key is missing, +the CLI reports the missing key on stderr and exits with status 1. +Run the skill's script in an isolated sandbox such as Docker/AIO, the Kubernetes provisioner, or E2B, and pass the variables through `sandbox.environment`. Sandbox commands do not inherit API keys from the Gateway process. diff --git a/skills/public/image-generation/SKILL.md b/skills/public/image-generation/SKILL.md index 3dcc64ef24..ceabf5eae5 100644 --- a/skills/public/image-generation/SKILL.md +++ b/skills/public/image-generation/SKILL.md @@ -159,6 +159,9 @@ Gemini image data is base64-decoded before the output directory or file is created. If decoding fails, an existing output image is preserved and no empty output file is left behind. +The OpenAI-compatible path rejects an empty download or an empty data URL before +the output directory or file is created, so an existing image is preserved too. + The legacy MiniMax `/v1/image_generation` writer opens the destination before decoding. If decoding fails, it can leave an empty file or erase an existing image. Use a fresh `--output-file` path when you need to keep the previous image. @@ -199,6 +202,7 @@ This skill auto-selects the provider by environment variables (no CLI change): - Otherwise, `IMAGE_GENERATION_API_KEY` set → use an OpenAI-compatible Images API. - Force one explicitly with `IMAGE_GENERATION_PROVIDER=gemini|minimax|openai`. `openai-compatible` is also accepted as an alias for `openai`. + If the selected provider's key is missing, the CLI names it on stderr and exits with status 1. OpenAI-compatible settings: @@ -236,8 +240,9 @@ the same structured JSON regardless of which provider is active. MiniMax `image- consumes a single text string, so the MiniMax path itself sends only the JSON `prompt` field (the other fields such as `style` / `composition` / `negative_prompt` apply to the Gemini path) and enables `prompt_optimizer` so MiniMax expands it server-side. MiniMax -caps that prompt at 1500 characters; if the `prompt` field is longer, the script returns -an error instead of calling the API. The Gemini path receives the full structured JSON. +accepts prompts up to 1500 characters. For longer prompts, the CLI reports the length +limit on stderr and exits with status 1 before contacting MiniMax or writing the image. +The Gemini path receives the full structured JSON. ## Notes diff --git a/skills/public/image-generation/scripts/generate.py b/skills/public/image-generation/scripts/generate.py index 42fa9fc88c..8d841bea1e 100644 --- a/skills/public/image-generation/scripts/generate.py +++ b/skills/public/image-generation/scripts/generate.py @@ -264,10 +264,10 @@ def _generate_image_minimax( ) -> str: bearer_value = os.getenv("MINIMAX_API_KEY") if not bearer_value: - return "MINIMAX_API_KEY is not set" + raise ValueError("MINIMAX_API_KEY is not set") prompt = _minimax_prompt(prompt) if len(prompt) > MINIMAX_PROMPT_MAX_CHARS: - return ( + raise ValueError( f"Prompt is {len(prompt)} characters but MiniMax image-01 accepts at most " f"{MINIMAX_PROMPT_MAX_CHARS}. Shorten the prompt to stay within the limit; " f"reference images plus a tighter description usually recover the detail." @@ -310,6 +310,10 @@ def _generate_image_minimax( def _generate_image_gemini( prompt: str, reference_images: list[str], output_file: str, aspect_ratio: str ) -> str: + bearer_value = os.getenv("GEMINI_API_KEY") + if not bearer_value: + raise ValueError("GEMINI_API_KEY is not set") + parts = [] valid_reference_images = [] for ref_img in reference_images: @@ -328,9 +332,6 @@ def _generate_image_gemini( image_b64 = base64.b64encode(f.read()).decode("utf-8") parts.append({"inlineData": {"mimeType": "image/jpeg", "data": image_b64}}) - bearer_value = os.getenv("GEMINI_API_KEY") - if not bearer_value: - return "GEMINI_API_KEY is not set" response = _post_image( "https://generativelanguage.googleapis.com/v1beta/models/gemini-3-pro-image-preview:generateContent", headers={"x-goog-api-key": bearer_value, "Content-Type": "application/json"}, @@ -373,6 +374,11 @@ def _write_openai_image(payload: dict, output_file: str) -> str: else: image_bytes = _download_image(image_url) + # A provider can answer 200 with no bytes, or hand back an empty data URL. + # Fail before the output is opened so an existing image is preserved. + if not image_bytes: + raise ValueError("Provider returned an empty image") + _ensure_output_dir(output_file) with open(output_file, "wb") as f: f.write(image_bytes) @@ -384,7 +390,7 @@ def _generate_image_openai( ) -> str: bearer_value = os.getenv("IMAGE_GENERATION_API_KEY") if not bearer_value: - return "IMAGE_GENERATION_API_KEY is not set" + raise ValueError("IMAGE_GENERATION_API_KEY is not set") url = f"{_openai_base_url()}/images/generations" headers = {"Authorization": f"Bearer {bearer_value}"} diff --git a/skills/public/ppt-generation/SKILL.md b/skills/public/ppt-generation/SKILL.md index 0b3930426a..725aae7abd 100644 --- a/skills/public/ppt-generation/SKILL.md +++ b/skills/public/ppt-generation/SKILL.md @@ -124,17 +124,14 @@ python /mnt/skills/public/image-generation/scripts/generate.py \ --aspect-ratio 16:9 ``` -4. **Continue for all remaining slides**, always referencing the previous slide: +4. **Continue for all remaining slides**. Use the previous slide as a reference only after the script reports that it generated that slide. A failed attempt can leave an older image at the same path. ```bash -# Slide 3 references slide 2 python /mnt/skills/public/image-generation/scripts/generate.py \ --prompt-file /mnt/user-data/workspace/slide-03-prompt.json \ --reference-images /mnt/user-data/outputs/slide-02.jpg \ --output-file /mnt/user-data/outputs/slide-03.jpg \ - --aspect-ratio 16:9 - -# Slide 4 references slide 3 + --aspect-ratio 16:9 && python /mnt/skills/public/image-generation/scripts/generate.py \ --prompt-file /mnt/user-data/workspace/slide-04-prompt.json \ --reference-images /mnt/user-data/outputs/slide-03.jpg \ diff --git a/tests/skills/test_image_generation.py b/tests/skills/test_image_generation.py index 1d0f2284a9..4e405147b6 100644 --- a/tests/skills/test_image_generation.py +++ b/tests/skills/test_image_generation.py @@ -71,6 +71,56 @@ def test_resolve_errors_when_none(monkeypatch): img._resolve_provider("IMAGE_GENERATION_PROVIDER", "gemini", False) +@pytest.mark.parametrize( + ("provider", "missing_key"), + [ + ("minimax", "MINIMAX_API_KEY"), + ("gemini", "GEMINI_API_KEY"), + ("google", "GEMINI_API_KEY"), + ("openai", "IMAGE_GENERATION_API_KEY"), + ("openai-compatible", "IMAGE_GENERATION_API_KEY"), + ], +) +def test_cli_forced_provider_requires_its_key( + monkeypatch, tmp_path, capsys, provider, missing_key +): + monkeypatch.setenv("IMAGE_GENERATION_PROVIDER", provider) + for key in ("GEMINI_API_KEY", "MINIMAX_API_KEY", "IMAGE_GENERATION_API_KEY"): + monkeypatch.setenv(key, "test-key") + monkeypatch.delenv(missing_key) + + def unexpected_post(*args, **kwargs): + pytest.fail("A missing provider key must stop the request") + + monkeypatch.setattr(img.requests, "post", unexpected_post) + prompt = tmp_path / "prompt.txt" + prompt.write_text("a red deer", encoding="utf-8") + output = tmp_path / "slide-03.jpg" + output.write_bytes(b"previous slide") + monkeypatch.setattr( + sys, + "argv", + [ + img.__file__, + "--prompt-file", + str(prompt), + "--reference-images", + str(tmp_path / "missing-reference.jpg"), + "--output-file", + str(output), + ], + ) + + with pytest.raises(SystemExit) as error: + runpy.run_path(img.__file__, run_name="__main__") + + assert error.value.code == 1 + captured = capsys.readouterr() + assert f"{missing_key} is not set" in captured.err + assert not captured.out + assert output.read_bytes() == b"previous slide" + + def test_minimax_builds_payload_and_writes(monkeypatch, tmp_path): monkeypatch.setenv("MINIMAX_API_KEY", "m") raw = b"PNGBYTES" @@ -176,7 +226,10 @@ def test_minimax_extracts_json_prompt_field(monkeypatch, tmp_path): assert captured["json"]["prompt_optimizer"] is True -def test_minimax_plaintext_prompt_passes_through(monkeypatch, tmp_path): +@pytest.mark.parametrize( + "prompt", ["a red apple on a table", "x" * 1500], ids=["short", "at-limit"] +) +def test_minimax_plaintext_prompt_passes_through(monkeypatch, tmp_path, prompt): monkeypatch.setenv("MINIMAX_API_KEY", "m") captured = {} @@ -191,27 +244,46 @@ def test_minimax_plaintext_prompt_passes_through(monkeypatch, tmp_path): monkeypatch.setattr(img.requests, "post", fake_post) prompt_file = tmp_path / "p.txt" - prompt_file.write_text("a red apple on a table", encoding="utf-8") + prompt_file.write_text(prompt, encoding="utf-8") img.generate_image(str(prompt_file), [], str(tmp_path / "o.jpg"), "1:1") - assert captured["json"]["prompt"] == "a red apple on a table" + assert captured["json"]["prompt"] == prompt -def test_minimax_rejects_overlong_prompt_without_calling_api(monkeypatch, tmp_path): +@pytest.mark.parametrize( + "existing", [False, True], ids=["new-output", "existing-output"] +) +def test_cli_minimax_rejects_overlong_prompt(monkeypatch, tmp_path, capsys, existing): monkeypatch.setenv("MINIMAX_API_KEY", "m") - def fake_post(url, headers=None, json=None, **kw): # pragma: no cover - raise AssertionError("must not call the API when the prompt is over the limit") + def fake_post(*args, **kwargs): + pytest.fail("Overlong prompts must be rejected before calling MiniMax") monkeypatch.setattr(img.requests, "post", fake_post) prompt_file = tmp_path / "p.json" - prompt_file.write_text('{"prompt": "' + "x" * 1600 + '"}', encoding="utf-8") + prompt_file.write_text('{"prompt": "' + "x" * 1501 + '"}', encoding="utf-8") out = tmp_path / "o.jpg" - msg = img.generate_image(str(prompt_file), [], str(out), "16:9") + if existing: + out.write_bytes(b"previous image") + monkeypatch.setattr( + sys, + "argv", + [img.__file__, "--prompt-file", str(prompt_file), "--output-file", str(out)], + ) - assert "1500" in msg - assert "character" in msg.lower() - assert not out.exists() + with pytest.raises(SystemExit) as error: + runpy.run_path(img.__file__, run_name="__main__") + + assert error.value.code == 1 + captured = capsys.readouterr() + assert not captured.out + assert "1501 characters" in captured.err + assert "at most 1500" in captured.err + assert "Shorten the prompt" in captured.err + if existing: + assert out.read_bytes() == b"previous image" + else: + assert not out.exists() def test_minimax_creates_nested_output_dir(monkeypatch, tmp_path): @@ -457,6 +529,69 @@ def test_openai_compatible_download_requires_2xx( assert not output.exists() +@pytest.mark.parametrize( + "existing", [False, True], ids=["new-output", "existing-output"] +) +def test_openai_compatible_empty_download_preserves_output( + monkeypatch, tmp_path, existing +): + monkeypatch.setenv("IMAGE_GENERATION_PROVIDER", "openai") + monkeypatch.setenv("IMAGE_GENERATION_API_KEY", "image-key") + monkeypatch.setattr( + img.requests, + "post", + lambda *args, **kwargs: FakeResp( + {"data": [{"url": "https://cdn.example/image.png"}]} + ), + ) + monkeypatch.setattr( + img.requests, + "get", + lambda *args, **kwargs: FakeResp(content=b""), + ) + prompt = tmp_path / "prompt.txt" + prompt.write_text("a red deer", encoding="utf-8") + output = tmp_path / "outputs" / "image.png" + if existing: + output.parent.mkdir() + output.write_bytes(b"previous image") + + with pytest.raises(ValueError, match="empty image"): + img.generate_image(str(prompt), [], str(output)) + if existing: + assert output.read_bytes() == b"previous image" + else: + assert not output.parent.exists() + + +@pytest.mark.parametrize( + "existing", [False, True], ids=["new-output", "existing-output"] +) +def test_openai_compatible_empty_data_url_preserves_output( + monkeypatch, tmp_path, existing +): + monkeypatch.setenv("IMAGE_GENERATION_PROVIDER", "openai") + monkeypatch.setenv("IMAGE_GENERATION_API_KEY", "image-key") + monkeypatch.setattr( + img.requests, + "post", + lambda *args, **kwargs: FakeResp({"data": [{"url": "data:image/png;base64,"}]}), + ) + prompt = tmp_path / "prompt.txt" + prompt.write_text("a red deer", encoding="utf-8") + output = tmp_path / "outputs" / "image.png" + if existing: + output.parent.mkdir() + output.write_bytes(b"previous image") + + with pytest.raises(ValueError, match="empty image"): + img.generate_image(str(prompt), [], str(output)) + if existing: + assert output.read_bytes() == b"previous image" + else: + assert not output.parent.exists() + + @pytest.mark.parametrize( ("provider", "key", "edit"), [