The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(image_gen): embed local Krea style references so files from disk work outside a sandbox
Mariano Nicolinif5928fe0033f
diff --git a/plugins/image_gen/krea/__init__.py b/plugins/image_gen/krea/__init__.pyindex 71d3960f5ae..295b25054e6 100644--- a/plugins/image_gen/krea/__init__.py+++ b/plugins/image_gen/krea/__init__.py@@ -9,9 +9,13 @@ of our IDs) → :data:`DEFAULT_MODEL`. Docs: https://docs.krea.ai/developers/krefrom __future__ import annotations+import base64import logging+import mimetypes+import osimport timeimport uuid+from pathlib import Pathfrom typing import Any, Callable, Dict, List, Optional, Tupleimport requests@@ -57,6 +61,9 @@ DEFAULT_RESOLUTION = "1K" # only resolution Krea currently supports# Style refs are objects ({"url", "strength"}); bare URLs get Krea's recommended start (range -2..2)._DEFAULT_STYLE_REFERENCE_STRENGTH = 0.6_MAX_STYLE_REFERENCES = 10+_REMOTE_REFERENCE_PREFIXES = ("http://", "https://", "data:")+# Base64 grows a file by a third and the managed gateway rejects bodies over about 4.5 MB.+_MAX_LOCAL_REFERENCE_BYTES = 3 * 1024 * 1024_VALID_CREATIVITY = {"raw", "low", "medium", "high"}# Polling: Krea recommends 2-5s; 2s backing off to 5s (Large ~1min); ceiling = Krea's 3 min tool timeout.@@ -306,6 +313,32 @@ def _collect_style_refs(return deduped[:_MAX_STYLE_REFERENCES]+def _inline_local_style_refs(+ style_refs: List[Any], fail: ErrorFn+) -> Tuple[List[Any], Optional[Dict[str, Any]]]:+ """Embed local image files as data URIs; URLs and data URIs pass through unchanged."""+ from agent.file_safety import raise_if_read_blocked++ inlined: List[Any] = []+ for ref in style_refs:+ source = ref.get("url") if isinstance(ref, dict) else ref+ if not isinstance(source, str) or source.lower().startswith(_REMOTE_REFERENCE_PREFIXES):+ inlined.append(ref)+ continue+ path = Path(os.path.expanduser(source))+ if not path.is_file():+ return [], fail(f"Style reference image not found: {source}", "invalid_image_url")+ if path.stat().st_size > _MAX_LOCAL_REFERENCE_BYTES:+ return [], fail(+ f"Style reference image {source} is over 3 MB; resize it or pass a public URL",+ "source_too_large")+ raise_if_read_blocked(str(path))+ mime = mimetypes.guess_type(path.name)[0] or "image/png"+ data_uri = f"data:{mime};base64,{base64.b64encode(path.read_bytes()).decode('ascii')}"+ inlined.append({**ref, "url": data_uri} if isinstance(ref, dict) else data_uri)+ return inlined, None++def _build_payload(prompt: str, krea_ar: str, creativity: str, style_refs: List[Any], kwargs: Dict[str, Any]) -> Dict[str, Any]:@@ -446,6 +479,9 @@ class KreaImageGenProvider(StaticImageGenProvider):model_id, meta = _resolve_model(kwargs.get("model"))creativity = _resolve_creativity(kwargs.get("creativity"))fail = error_factory("krea", aspect, model=model_id, prompt=prompt)+ style_refs, err = _inline_local_style_refs(style_refs, fail)+ if err is not None:+ return errpayload = _build_payload(prompt, krea_ar, creativity, style_refs, kwargs)# LoRAs/moodboards are rejected by the managed gateway: fail fast with guidance, not a raw 400.diff --git a/tests/plugins/image_gen/test_krea_provider.py b/tests/plugins/image_gen/test_krea_provider.pyindex aa5d7622588..c187617b602 100644--- a/tests/plugins/image_gen/test_krea_provider.py+++ b/tests/plugins/image_gen/test_krea_provider.py@@ -3,6 +3,7 @@from __future__ import annotations+import base64from pathlib import Pathfrom unittest.mock import MagicMock, patch@@ -262,6 +263,47 @@ class TestGenerate:{"url": "https://x.com/b.png", "strength": 1.2},]+ def test_local_style_reference_is_embedded_as_data_uri(self, tmp_path):+ from plugins.image_gen.krea import KreaImageGenProvider++ image = tmp_path / "ref.png"+ image.write_bytes(b"\x89PNG\r\n\x1a\nfake-image-bytes")+ submit = _submit_response()+ poll = _poll_response(_completed_job())++ with patch("plugins.image_gen.krea.requests.post", return_value=submit) as mock_post, \+ patch("plugins.image_gen.krea.requests.get", return_value=poll), \+ patch("plugins.image_gen.krea.save_url_image", return_value=Path("/tmp/x.png")), \+ patch("plugins.image_gen.krea.time.sleep"):+ KreaImageGenProvider().generate(prompt="test", image_url=str(image), upscale=False)++ [ref] = mock_post.call_args.kwargs["json"]["image_style_references"]+ expected = "data:image/png;base64," + base64.b64encode(image.read_bytes()).decode("ascii")+ assert ref == {"url": expected, "strength": 0.6}++ def test_oversized_local_style_reference_is_refused_before_submit(self, tmp_path, monkeypatch):+ from plugins.image_gen import krea++ monkeypatch.setattr(krea, "_MAX_LOCAL_REFERENCE_BYTES", 4)+ image = tmp_path / "big.png"+ image.write_bytes(b"\x89PNG\r\n\x1a\n")++ with patch("plugins.image_gen.krea.requests.post") as mock_post:+ result = krea.KreaImageGenProvider().generate(prompt="test", image_url=str(image))++ assert result["error_type"] == "source_too_large"+ mock_post.assert_not_called()++ def test_missing_local_style_reference_is_refused_before_submit(self):+ from plugins.image_gen.krea import KreaImageGenProvider++ with patch("plugins.image_gen.krea.requests.post") as mock_post:+ result = KreaImageGenProvider().generate(+ prompt="test", reference_image_urls=["/nowhere/ref.png"])++ assert result["error_type"] == "invalid_image_url"+ mock_post.assert_not_called()+def test_unknown_kwargs_ignored(self):"""Forward-compat: unknown kwargs must not break generate()."""from plugins.image_gen.krea import KreaImageGenProviderdiff --git a/website/docs/user-guide/features/image-generation.md b/website/docs/user-guide/features/image-generation.mdindex 2c9bd620b39..88bd66d099e 100644--- a/website/docs/user-guide/features/image-generation.md+++ b/website/docs/user-guide/features/image-generation.md@@ -290,7 +290,7 @@ Two inputs drive the edit:| **FAL.ai** (edit-capable models below) | ✓ | up to 16 (per model) | routes to the model's `/edit` endpoint || **OpenAI** (GPT Image 2 / 2.5 Flare / Sunburst) | ✓ | up to 16 | `images.edit()` || **xAI** (Grok Imagine) | ✓ | 1 | `/v1/images/edits` (`grok-imagine-image-quality`) |-| **Krea** (`Krea 2`) | ✓ | up to 10 | reference-guided generation (`image_style_references`) |+| **Krea** (`Krea 2`) | ✓ | up to 10 | reference-guided generation (`image_style_references`); local files up to 3 MB are embedded in the request || **OpenAI (Codex auth)** | ✓ | up to 16 | `POST /backend-api/codex/images/edits` with inline `images[]` data URLs (remote URLs are fetched client-side) || **OpenRouter** (Image API models) | ✓ | up to 14–16 (per model) | `input_references` on `POST /images/generations`; chat-served models use `image_url` content parts (up to 3) |