Skip to content

Open-source design agent: on-brand stills, decks, diagrams, charts and motion graphics from a chat thread, built on Deep Agents.

Google image generation with Gemini image models (#50)

Katta Karthike45f19f69c15
diff --git a/.env.example b/.env.example
index 309ab9a..05591b5 100644
--- a/.env.example
+++ b/.env.example
@@ -14,8 +14,8 @@ DESIGN_AGENT_MODEL_TIMEOUT_SECONDS=600 # one call's stall ceiling
DESIGN_AGENT_MODEL_BASE_URL=
DESIGN_AGENT_MODEL_API_KEY_ENV=
ANTHROPIC_API_KEY=
-OPENAI_API_KEY= # images; without it, images go through the gateway when you use it
-GOOGLE_API_KEY=
+OPENAI_API_KEY= # images (OpenAI)
+GOOGLE_API_KEY= # Gemini models; images too when there is no OpenAI key
LANGSMITH_API_KEY= # MDA deploy/dev, LangSmith sandboxes, tracing, optional gateway
LANGSMITH_GATEWAY_API_KEY=
@@ -42,7 +42,7 @@ DESIGN_AGENT_BRAND_PATH=workspace/brand # falls back to examples/brands/examp
DESIGN_AGENT_PRIVATE_FONTS_DIR=private-fonts
# Media (optional)
-DESIGN_AGENT_IMAGE_MODEL=gpt-image-2.5-flare
+DESIGN_AGENT_IMAGE_MODEL=gpt-image-2.5-flare # or gemini-nano-banana-2.1 to make images with Google
ELEVENLABS_API_KEY=
GROQ_API_KEY=
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 33387dd..e8cf12a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,10 @@
### Added
+- Images from Google's Gemini image models (from #50): with `GOOGLE_API_KEY`, or through the
+ LangSmith Gateway's Google path when the lead model is Google. `DESIGN_AGENT_IMAGE_MODEL=gemini-…`
+ picks Google whenever it is reachable. A key only goes to its own provider or the gateway, and
+ only a well-formed Gemini model id reaches the request URL.
- Image generation goes through the LangSmith Gateway when there is no `OPENAI_API_KEY` and the
deployment uses the gateway (a `langsmith:` model or `LANGSMITH_GATEWAY_API_KEY`); a gateway
workspace with no OpenAI key says so.
diff --git a/README.md b/README.md
index 75c00d6..10df8fa 100644
--- a/README.md
+++ b/README.md
@@ -205,7 +205,7 @@ what Content Studio reads while it works. [Customization](docs/customization.md)
| Want | Add | Guide |
| --- | --- | --- |
| Your brand | `workspace/brand/` (until then, a neutral sample brand), then redeploy | [brand-onboarding skill](.agents/skills/brand-onboarding/SKILL.md) |
-| Generated images | `OPENAI_API_KEY`, or the LangSmith Gateway | [Models](docs/models.md) |
+| Generated images | `OPENAI_API_KEY`, `GOOGLE_API_KEY`, or the LangSmith Gateway | [Models](docs/models.md) |
| Voice, music, sound effects | `ELEVENLABS_API_KEY` | [sound skill](skills/sound/SKILL.md) |
| The Paper canvas | `PAPER_MODE=local` with Paper Desktop, or `bridged` when deployed | [Paper](docs/partners/paper.md) |
| Web search, your docs, other tools | MCP servers in `config/mcp.toml` | [Customization](docs/customization.md) |
diff --git a/docs/models.md b/docs/models.md
index bb8ca43..0466ac0 100644
--- a/docs/models.md
+++ b/docs/models.md
@@ -12,10 +12,13 @@ ANTHROPIC_API_KEY=…
default; Google, Groq and Mistral are extras (`uv sync --extra google`). The LangSmith Gateway is an
optional preset (`langsmith:anthropic/claude-opus-5-5` with `LANGSMITH_GATEWAY_API_KEY`, else
`LANGSMITH_API_KEY`), never required. Anthropic and OpenAI models go through the gateway's native
-routes and keep every feature in the table below; other providers use its shared route. Image
-generation uses `OPENAI_API_KEY` when it is set; without it, a deployment that uses the gateway (a
-`langsmith:` model or `LANGSMITH_GATEWAY_API_KEY`) generates images through the gateway's OpenAI
-route, with the OpenAI key stored in that gateway workspace. For an OpenAI-compatible endpoint, set `DESIGN_AGENT_MODEL_BASE_URL` and
+routes and keep every feature in the table below; other providers use its shared route. Images
+come from the first of these that is set: `OPENAI_API_KEY` (OpenAI), `GOOGLE_API_KEY` (Google's
+Gemini image models), or, on a deployment that uses the gateway (a `langsmith:` model or
+`LANGSMITH_GATEWAY_API_KEY`), the gateway: its Google path when the lead model is Google, its OpenAI
+path otherwise, with the provider key stored in that gateway workspace.
+`DESIGN_AGENT_IMAGE_MODEL=gemini-…` (for example `gemini-nano-banana-2.1`) picks Google whenever
+Google is reachable. Google's image models make no transparent backgrounds. For an OpenAI-compatible endpoint, set `DESIGN_AGENT_MODEL_BASE_URL` and
`DESIGN_AGENT_MODEL_API_KEY_ENV` (the name of the variable that holds its key).
## Roles
diff --git a/skills/image-generation/SKILL.md b/skills/image-generation/SKILL.md
index 1763bbb..073249d 100644
--- a/skills/image-generation/SKILL.md
+++ b/skills/image-generation/SKILL.md
@@ -31,7 +31,9 @@ The tool runs on the host, so no key ever enters the sandbox; never call a provi
script. It writes the files (`_0`, `_1` suffixes when `n` > 1) and returns their paths. `model`,
`size`, `quality`, `n`, `background`, `output_format` and any extra `params` pass straight through to
the provider, which validates them and explains a refusal in its own words: read the message and
-adjust rather than guessing from memory what is allowed. Every call spends money: explore at low
+adjust rather than guessing from memory what is allowed. When the deployment makes images with
+Google, `size` becomes the nearest aspect ratio, `quality="high"` asks for 2K, and there is no
+transparent background: generate on a plain ground and cut the subject out. Every call spends money: explore at low
quality, finish once at high.
The prompt is the leverage: concrete subject, action, medium, light, composition, and "no text, no
diff --git a/src/design_agent/tools/media.py b/src/design_agent/tools/media.py
index ccc0d9e..064f206 100644
--- a/src/design_agent/tools/media.py
+++ b/src/design_agent/tools/media.py
@@ -7,6 +7,7 @@ Nothing here sends a file to the person; delivery is `upload_files`.
from __future__ import annotations
+import asyncio
import base64
import binascii
import json
@@ -16,7 +17,7 @@ import shlex
import struct
import zlib
from dataclasses import dataclass
-from typing import Any
+from typing import Any, Literal
import httpx
from langchain.tools import ToolRuntime
@@ -41,13 +42,36 @@ ELEVENLABS_CAP_MB = 25 # five minutes of 320 kbps mp3 is about 12 MB
VOICE_ID = re.compile(r"[A-Za-z0-9]{10,40}")
+GOOGLE_API = "https://generativelanguage.googleapis.com/v1beta"
+#: The LangSmith Gateway's direct Google path, which passes Gemini API requests through.
+GATEWAY_GOOGLE = f"{GATEWAY_ORIGIN}/gemini/v1beta"
+#: Google makes images with Gemini image models through `generateContent` (Imagen is shut down).
+GOOGLE_IMAGE_MODEL = "gemini-nano-banana-2.1"
+#: A model id safe to put in the request path: never a value with `/`, `?`, `#` or `:`.
+GOOGLE_MODEL_ID = re.compile(r"gemini-[a-z0-9][a-z0-9.\-]*")
+GOOGLE_ASPECT_RATIOS = {
+ "1:1": 1.0,
+ "2:3": 2 / 3,
+ "3:2": 3 / 2,
+ "3:4": 3 / 4,
+ "4:3": 4 / 3,
+ "4:5": 4 / 5,
+ "5:4": 5 / 4,
+ "9:16": 9 / 16,
+ "16:9": 16 / 9,
+ "21:9": 21 / 9,
+}
+
+
@dataclass(frozen=True)
class ImageRoute:
- """Where image generation goes, with the key for it and a name for messages."""
+ """Where image generation goes, with the key for it and a name for messages. For OpenAI
+ `url` is the endpoint; for Google it is the models collection a model id is appended to."""
url: str
key: str
via: str
+ provider: Literal["openai", "google"] = "openai"
def _secret(secret: Any) -> str | None:
@@ -55,21 +79,51 @@ def _secret(secret: Any) -> str | None:
def image_route(settings: Settings) -> ImageRoute | None:
- """OpenAI with its own key; else the LangSmith Gateway's OpenAI route when this deployment uses
- the gateway (a gateway key, or a `langsmith:` lead model), which uses its workspace's OpenAI key."""
- if openai := _secret(settings.openai_api_key):
- return ImageRoute(f"{OPENAI_BASE_URL}/images/generations", openai, "OpenAI")
+ """A provider key you set wins: OpenAI's, then Google's. Without one, a deployment that uses the
+ LangSmith Gateway (a `langsmith:` model or `LANGSMITH_GATEWAY_API_KEY`) goes through it, to
+ Google when the lead model is Google and to OpenAI otherwise. `DESIGN_AGENT_IMAGE_MODEL=gemini-…`
+ picks Google whenever Google is reachable. A key only ever goes to its own provider or the
+ gateway."""
+ openai = _secret(settings.openai_api_key)
+ google = _secret(settings.google_api_key)
uses_gateway = bool(_secret(settings.langsmith_gateway_api_key))
+ lead_is_google = False
try:
- uses_gateway = uses_gateway or settings.lead_model().via_gateway
+ lead = settings.lead_model()
+ uses_gateway = uses_gateway or lead.via_gateway
+ provider = lead.upstream.provider if lead.via_gateway else lead.provider
+ lead_is_google = provider in ("google", "google_genai")
except ValueError:
pass
- if uses_gateway and (key := gateway_key(settings)):
+ gateway = gateway_key(settings) if uses_gateway else ""
+ wants_google = settings.image_model.startswith("gemini-") or (lead_is_google and not openai)
+ if wants_google and google:
+ return ImageRoute(f"{GOOGLE_API}/models", google, "Google", provider="google")
+ if wants_google and gateway:
+ return ImageRoute(
+ f"{GATEWAY_GOOGLE}/models", gateway, "the LangSmith Gateway", provider="google"
+ )
+ if openai:
+ return ImageRoute(f"{OPENAI_BASE_URL}/images/generations", openai, "OpenAI")
+ if google:
+ return ImageRoute(f"{GOOGLE_API}/models", google, "Google", provider="google")
+ if gateway:
url = f"{GATEWAY_ORIGIN}{GATEWAY_NATIVE_ROUTES['openai']}/images/generations"
- return ImageRoute(url, key, "the LangSmith Gateway")
+ return ImageRoute(url, gateway, "the LangSmith Gateway")
return None
+def _google_model(requested: str | None, configured: str) -> str:
+ """The Gemini image model to call: the requested or configured id when it is a valid Gemini
+ model id (an OpenAI name or anything malformed falls back), else Google's default."""
+ for candidate in (requested, configured):
+ clean = (candidate or "").strip().removeprefix("models/").removeprefix("google_genai/")
+ clean = clean.removeprefix("google/")
+ if GOOGLE_MODEL_ID.fullmatch(clean):
+ return clean
+ return GOOGLE_IMAGE_MODEL
+
+
@dataclass(frozen=True)
class MediaKeys:
"""Provider credentials, held only by host tools."""
@@ -174,17 +228,122 @@ def _word_timings(alignment: dict[str, list[Any]]) -> list[dict[str, JsonValue]]
def _reason(response: httpx.Response) -> str:
"""The provider's own reason for a refusal, which is what lets the model correct the call.
- OpenAI answers `{"error": {"message": ...}}`; the message names the bad field or value and
- carries no credential, so it is safe to hand back. Anything else reads as a bare status.
+ OpenAI answers `{"error": {"message": ...}}`; Google answers `{"error": {"message": ..., "status": ...}}`.
+ The message names the bad field or value and carries no credential, so it is safe to hand back.
+ Anything else reads as a bare status.
"""
try:
- message = response.json().get("error", {}).get("message")
+ payload = response.json()
+ error = payload.get("error")
+ message = None
+ if isinstance(error, dict):
+ detail_msgs: list[str] = []
+ if details := error.get("details"):
+ if isinstance(details, list):
+ for item in details:
+ if not isinstance(item, dict):
+ continue
+ for fv in item.get("fieldViolations", []):
+ if isinstance(fv, dict) and fv.get("description"):
+ field_prefix = f"{fv['field']}: " if fv.get("field") else ""
+ detail_msgs.append(f"{field_prefix}{fv['description']}")
+ for qv in item.get("violations", []):
+ if isinstance(qv, dict) and qv.get("description"):
+ detail_msgs.append(str(qv["description"]))
+ if item.get("reason") and not detail_msgs:
+ detail_msgs.append(str(item["reason"]))
+ if not detail_msgs and (item.get("description") or item.get("message")):
+ detail_msgs.append(str(item.get("description") or item.get("message")))
+
+ base_msg = error.get("message") or error.get("status")
+ if detail_msgs:
+ if (
+ base_msg
+ and base_msg not in detail_msgs
+ and base_msg != "Request contains an invalid argument."
+ ):
+ message = f"{base_msg} ({'; '.join(detail_msgs)})"
+ else:
+ message = "; ".join(detail_msgs)
+ else:
+ message = base_msg
+ elif isinstance(error, str):
+ message = error
+ elif isinstance(payload.get("message"), str):
+ message = payload.get("message")
except (ValueError, AttributeError):
return "."
- return f": {str(message)[:300]}" if message else "."
+ return f": {str(message).strip()[:300]}" if message else "."
+
+
+def _aspect_ratio_from_size(size: str) -> str:
+ """The supported Gemini aspect ratio closest to a size (`1792x1024`) or ratio (`16:9`)."""
+ text = size.strip().lower().replace("/", ":")
+ if text in GOOGLE_ASPECT_RATIOS:
+ return text
+ named = {
+ "square": "1:1",
+ "landscape": "16:9",
+ "wide": "16:9",
+ "portrait": "9:16",
+ "tall": "9:16",
+ }
+ if text in named:
+ return named[text]
+ for separator in ("x", ":"):
+ width, _, height = text.partition(separator)
+ try:
+ ratio = float(width) / float(height)
+ except (ValueError, ZeroDivisionError):
+ continue
+ if ratio > 0:
+ return min(
+ GOOGLE_ASPECT_RATIOS, key=lambda name: abs(GOOGLE_ASPECT_RATIOS[name] - ratio)
+ )
+ return "1:1"
_IMAGE_GEN_CAP_MB = 40 # a high-quality 4K PNG can be several MB; bound the downloaded response
+_IMAGE_EXTENSIONS = {
+ "image/png": (".png",),
+ "image/jpeg": (".jpg", ".jpeg"),
+ "image/webp": (".webp",),
+}
+
+
+def _gemini_images(payload: Any) -> tuple[list[tuple[bytes, str]], str]:
+ """The images in a Gemini `generateContent` answer, and Google's reason when there are none."""
+ images: list[tuple[bytes, str]] = []
+ reasons: list[str] = []
+ if not isinstance(payload, dict):
+ return images, ""
+ feedback = payload.get("promptFeedback")
+ if isinstance(feedback, dict) and feedback.get("blockReason"):
+ reasons.append(f"prompt blocked ({feedback['blockReason']})")
+ for candidate in payload.get("candidates") or []:
+ if not isinstance(candidate, dict):
+ continue
+ content = candidate.get("content")
+ parts = content.get("parts") if isinstance(content, dict) else None
+ found = False
+ for part in parts or []:
+ inline = part.get("inlineData") if isinstance(part, dict) else None
+ if not isinstance(inline, dict) or not inline.get("data"):
+ continue
+ encoded = str(inline["data"])
+ if len(encoded) > (_IMAGE_GEN_CAP_MB * 1024 * 1024 + 2) // 3 * 4:
+ reasons.append(f"image over {_IMAGE_GEN_CAP_MB} MB")
+ continue
+ images.append(
+ (base64.b64decode(encoded, validate=True), str(inline.get("mimeType") or ""))
+ )
+ found = True
+ finish = candidate.get("finishReason")
+ if not found and finish and finish != "STOP":
+ reasons.append(str(finish).lower())
+ return images, ", ".join(reasons)
+
+
_PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
_PNG_ALPHA_CHANNELS = {4: 2, 6: 4} # IHDR color type -> channels (gray+alpha, RGBA)
_PNG_SCAN_CAP_BYTES = 64 * 1024 * 1024 # inflate ceiling (~16M RGBA px); also the zip-bomb guard
@@ -577,7 +736,7 @@ def build_media_tools(settings: Settings, backend_for: BackendFor) -> list[BaseT
params: dict[str, JsonValue] | None = None,
model: str | None = None,
) -> str:
- """Generate images with OpenAI's image models and save them under /workspace.
+ """Generate images with OpenAI or Google image models and save them under /workspace.
Read the image-generation skill first. Anything with the logo or exact copy is built in
HTML on brand, not left to the image model: composite real text and logos afterwards.
@@ -592,58 +751,123 @@ def build_media_tools(settings: Settings, backend_for: BackendFor) -> list[BaseT
route = keys.image
if route is None:
return (
- "image generation unavailable: no OPENAI_API_KEY, and this deployment does not "
- "use the LangSmith Gateway."
+ "image generation unavailable: no OPENAI_API_KEY or GOOGLE_API_KEY, and this "
+ "deployment does not use the LangSmith Gateway."
)
- body: dict[str, JsonValue] = {
- "model": model or keys.image_model,
- "prompt": prompt,
- "size": size,
- "quality": quality,
- "n": n,
- }
- if background is not None:
- body["background"] = background
- if output_format is not None:
- body["output_format"] = output_format
- if params:
- body.update(params)
- wants_alpha = str(body.get("background", "")).strip().lower() == "transparent"
- async with httpx.AsyncClient(timeout=240, follow_redirects=False) as client:
- response = await client.post(
- route.url, headers={"Authorization": f"Bearer {route.key}"}, json=body
- )
- if response.status_code != 200:
- hint = (
- " (the gateway's workspace has no OpenAI key; add one there or set "
- "OPENAI_API_KEY)"
- if response.status_code == 424
- else ""
- )
- return (
- f"image generation failed: {route.via} HTTP {response.status_code}"
- f"{_reason(response)}{hint}"
- )
- items = response.json().get("data") or []
+ bg = (
+ background
+ if background is not None
+ else (params.get("background") if params else None)
+ )
+ wants_alpha = str(bg or "").strip().lower() == "transparent"
+ raw_images: list[tuple[bytes, str]] = []
+
+ if route.provider == "google":
+ image_config: dict[str, JsonValue] = {"aspectRatio": _aspect_ratio_from_size(size)}
+ if quality == "high":
+ image_config["imageSize"] = "2K"
+ for name, value in (params or {}).items():
+ field = {"aspect_ratio": "aspectRatio", "image_size": "imageSize"}.get(
+ name, name
+ )
+ if field in ("aspectRatio", "imageSize"):
+ image_config[field] = value
+ request: dict[str, JsonValue] = {
+ "contents": [{"role": "user", "parts": [{"text": prompt}]}],
+ "generationConfig": {
+ "responseModalities": ["IMAGE"],
+ "imageConfig": image_config,
+ },
+ }
+ url = f"{route.url}/{_google_model(model, keys.image_model)}:generateContent"
+ headers = {"x-goog-api-key": route.key}
+ # One image per call: `n` becomes up to four calls made together.
+ async with httpx.AsyncClient(timeout=240, follow_redirects=False) as client:
+ responses = await asyncio.gather(
+ *(
+ client.post(url, headers=headers, json=request)
+ for _ in range(max(1, min(n, 4)))
+ )
+ )
+ refusals: list[str] = []
+ for response in responses:
+ if response.status_code != 200:
+ hint = (
+ " (the gateway's workspace has no Google key; add one there or set "
+ "GOOGLE_API_KEY)"
+ if response.status_code == 424
+ else ""
+ )
+ return (
+ f"image generation failed: {route.via} HTTP {response.status_code}"
+ f"{_reason(response)}{hint}"
+ )
+ images, refusal = _gemini_images(response.json())
+ raw_images.extend(images)
+ if refusal:
+ refusals.append(refusal)
+ if not raw_images and refusals:
+ return f"image generation refused by Google: {'; '.join(refusals)}."
+ else:
+ body: dict[str, JsonValue] = {
+ "model": model or keys.image_model,
+ "prompt": prompt,
+ "size": size,
+ "quality": quality,
+ "n": n,
+ }
+ if background is not None:
+ body["background"] = background
+ if output_format is not None:
+ body["output_format"] = output_format
+ if params:
+ body.update(params)
+ async with httpx.AsyncClient(timeout=240, follow_redirects=False) as client:
+ response = await client.post(
+ route.url, headers={"Authorization": f"Bearer {route.key}"}, json=body
+ )
+ if response.status_code != 200:
+ hint = (
+ " (the gateway's workspace has no OpenAI key; add one there or set "
+ "OPENAI_API_KEY)"
+ if response.status_code == 424
+ else ""
+ )
+ return (
+ f"image generation failed: {route.via} HTTP {response.status_code}"
+ f"{_reason(response)}{hint}"
+ )
+ items = response.json().get("data") or []
+ for item in items:
+ if not isinstance(item, dict):
+ continue
+ if item.get("b64_json"):
+ encoded = item["b64_json"]
+ if len(encoded) > (_IMAGE_GEN_CAP_MB * 1024 * 1024 + 2) // 3 * 4:
+ return f"generated image too large: limit {_IMAGE_GEN_CAP_MB} MB."
+ raw_images.append((base64.b64decode(encoded, validate=True), ""))
+ elif item.get("url"):
+ data = await _download(
+ item["url"], cap_mb=_IMAGE_GEN_CAP_MB, provider="OpenAI image"
+ )
+ raw_images.append((data, ""))
+
written: list[str] = []
reports: list[str] = []
- for index, item in enumerate(items):
- if item.get("b64_json"):
- encoded = item["b64_json"]
- if len(encoded) > (_IMAGE_GEN_CAP_MB * 1024 * 1024 + 2) // 3 * 4:
- return f"generated image too large: limit {_IMAGE_GEN_CAP_MB} MB."
- data = base64.b64decode(encoded, validate=True)
- elif item.get("url"):
- data = await _download(
- item["url"], cap_mb=_IMAGE_GEN_CAP_MB, provider="OpenAI image"
- )
- else:
- continue
- stem, extension = posixpath.splitext(path)
- target = f"{stem}_{index}{extension}" if len(items) > 1 else path
+ stem, extension = posixpath.splitext(path)
+ for index, (data, mime) in enumerate(raw_images):
+ # Google answers in its own format: name the file for what it holds.
+ kinds = _IMAGE_EXTENSIONS.get(mime, ())
+ suffix = extension if not kinds or extension.lower() in kinds else kinds[0]
+ target = f"{stem}_{index}{suffix}" if len(raw_images) > 1 else stem + suffix
written.append(await write_bytes(backend, target, data))
if wants_alpha:
reports.append(_alpha_receipt(target, *_png_alpha_report(data)))
+ if written and wants_alpha and route.provider == "google":
+ reports.append(
+ "Google's image models make no transparent backgrounds: generate on a plain "
+ "ground and cut the subject out."
+ )
return (
"\n".join(["wrote " + ", ".join(written), *reports])
if written
diff --git a/tests/unit/test_host_tools.py b/tests/unit/test_host_tools.py
index 9300968..0c6872e 100644
--- a/tests/unit/test_host_tools.py
+++ b/tests/unit/test_host_tools.py
@@ -14,7 +14,15 @@ from deepagents.backends.protocol import FileDownloadResponse, FileUploadRespons
from design_agent.config import Settings
from design_agent.tools.fetch import FetchRefused, build_fetch_tool, check_url, public_address
-from design_agent.tools.media import _png_alpha_report, build_media_tools, image_route
+from design_agent.tools.media import (
+ GATEWAY_GOOGLE,
+ GOOGLE_API,
+ GOOGLE_IMAGE_MODEL,
+ _google_model,
+ _png_alpha_report,
+ build_media_tools,
+ image_route,
+)
class MemoryBackend:
@@ -231,3 +239,148 @@ async def test_a_gateway_without_an_openai_key_says_where_to_add_one(
) # type: ignore[misc]
assert "LangSmith Gateway HTTP 424" in result and "no OpenAI key" in result
assert not backend.files
+
+
+def test_images_pick_a_provider_and_a_key_never_crosses_to_another() -> None:
+ google = image_route(_settings(google_api_key="aiza-direct"))
+ assert google is not None and google.provider == "google"
+ assert google.url == f"{GOOGLE_API}/models" and google.key == "aiza-direct"
+
+ # A Google lead on the gateway goes through the gateway's Google path with the LangSmith key;
+ # the LangSmith key never goes to Google itself.
+ for settings in (
+ _settings(model="langsmith:google_genai/gemini-3.8-flash", langsmith_api_key="lsv2-l"),
+ _settings(model="google_genai:gemini-3.8-flash", langsmith_gateway_api_key="lsv2-l"),
+ ):
+ via_gateway = image_route(settings)
+ assert via_gateway is not None and via_gateway.provider == "google"
+ assert via_gateway.url == f"{GATEWAY_GOOGLE}/models" and via_gateway.key == "lsv2-l"
+ assert "googleapis.com" not in via_gateway.url
+
+ anthropic_lead = image_route(
+ _settings(model="langsmith:anthropic/claude-opus-5-5", langsmith_api_key="lsv2-l")
+ )
+ assert anthropic_lead is not None and anthropic_lead.provider == "openai"
+
+ # A provider key you set wins; DESIGN_AGENT_IMAGE_MODEL=gemini-… chooses Google outright.
+ both = _settings(openai_api_key="sk-test", google_api_key="aiza-direct")
+ assert image_route(both).provider == "openai" # type: ignore[union-attr]
+ chosen = _settings(
+ openai_api_key="sk-test", google_api_key="aiza-direct", image_model="gemini-3-pro-image"
+ )
+ assert image_route(chosen).provider == "google" # type: ignore[union-attr]
+
+
+ ("requested", "configured", "model"),
+ [
+ ("gemini-3-pro-image", "gpt-image-2.5-flare", "gemini-3-pro-image"),
+ ("models/gemini-3.1-flash-image", "gpt-image-2.5-flare", "gemini-3.1-flash-image"),
+ (None, "gemini-3.1-flash-lite-image", "gemini-3.1-flash-lite-image"),
+ ("gpt-image-2.5-flare", "gpt-image-2.5-flare", GOOGLE_IMAGE_MODEL),
+ ("gemini-x:generateContent?alt=sse#", "gpt-image-2.5-flare", GOOGLE_IMAGE_MODEL),
+ ("gemini-x/../../files", "gpt-image-2.5-flare", GOOGLE_IMAGE_MODEL),
+ ],
+)
+def test_only_a_well_formed_gemini_model_id_reaches_the_url(
+ requested: str | None, configured: str, model: str
+) -> None:
+ assert _google_model(requested, configured) == model
+
+
+def _gemini(*images: bytes, mime: str = "image/png") -> dict[str, Any]:
+ parts = [
+ {"inlineData": {"mimeType": mime, "data": base64.b64encode(image).decode()}}
+ for image in images
+ ]
+ return {"candidates": [{"content": {"parts": parts}, "finishReason": "STOP"}]}
+
+
+def _google_tools(
+ monkeypatch: pytest.MonkeyPatch, answer: Any, status: int = 200, **settings: Any
+) -> tuple[dict[str, Any], list[dict[str, Any]], Any]:
+ calls: list[dict[str, Any]] = []
+
+ async def fake_post(self: httpx.AsyncClient, url: str, **kwargs: Any) -> httpx.Response:
+ calls.append({"url": url, **kwargs})
+ return httpx.Response(
+ status, content=json.dumps(answer).encode(), request=httpx.Request("POST", url)
+ )
+
+ monkeypatch.setattr(httpx.AsyncClient, "post", fake_post)
+ backend = MemoryBackend()
+ tools = {
+ t.name: t
+ for t in build_media_tools(
+ _settings(**({"google_api_key": "aiza-test"} | settings)), lambda _rt: backend
+ )
+ } # type: ignore[arg-type,return-value]
+ return tools, calls, backend
+
+
+async def test_google_images_come_from_generate_content(monkeypatch: pytest.MonkeyPatch) -> None:
+ tools, calls, backend = _google_tools(monkeypatch, _gemini(_png(2, 2, 255)))
+ result = await tools["generate_image"].coroutine(
+ prompt="a lamp",
+ sandbox_path="/workspace/projects/p/lamp.jpg",
+ runtime=None,
+ size="1792x1024",
+ n=2,
+ background="transparent",
+ ) # type: ignore[misc]
+ assert len(calls) == 2
+ (call, _) = calls
+ assert call["url"] == f"{GOOGLE_API}/models/{GOOGLE_IMAGE_MODEL}:generateContent"
+ assert call["headers"] == {"x-goog-api-key": "aiza-test"}
+ config = call["json"]["generationConfig"]
+ assert config["responseModalities"] == ["IMAGE"]
+ assert config["imageConfig"]["aspectRatio"] == "16:9"
+ # Google answered PNG, so the files say so.
+ assert sorted(backend.files) == [
+ "/workspace/projects/p/lamp_0.png",
+ "/workspace/projects/p/lamp_1.png",
+ ]
+ assert "no transparent backgrounds" in result
+
+
+async def test_google_refusals_and_errors_say_why(monkeypatch: pytest.MonkeyPatch) -> None:
+ blocked = {"promptFeedback": {"blockReason": "SAFETY"}, "candidates": []}
+ tools, _, backend = _google_tools(monkeypatch, blocked)
+ result = await tools["generate_image"].coroutine(
+ prompt="x", sandbox_path="/workspace/projects/p/x.png", runtime=None
+ ) # type: ignore[misc]
+ assert result == "image generation refused by Google: prompt blocked (SAFETY)."
+ assert not backend.files
+
+ invalid = {
+ "error": {
+ "message": "Request contains an invalid argument.",
+ "details": [
+ {
+ "@type": "type.googleapis.com/google.rpc.BadRequest",
+ "fieldViolations": [
+ {"field": "imageConfig.aspectRatio", "description": "unsupported"}
+ ],
+ }
+ ],
+ }
+ }
+ tools, _, _ = _google_tools(monkeypatch, invalid, status=400)
+ result = await tools["generate_image"].coroutine(
+ prompt="x", sandbox_path="/workspace/projects/p/x.png", runtime=None
+ ) # type: ignore[misc]
+ assert "Google HTTP 400: imageConfig.aspectRatio: unsupported" in result
+
+ tools, calls, _ = _google_tools(
+ monkeypatch,
+ {},
+ status=424,
+ google_api_key=None,
+ model="langsmith:google_genai/gemini-3.8-flash",
+ langsmith_api_key="lsv2-l",
+ )
+ result = await tools["generate_image"].coroutine(
+ prompt="x", sandbox_path="/workspace/projects/p/x.png", runtime=None
+ ) # type: ignore[misc]
+ assert calls[0]["url"].startswith(GATEWAY_GOOGLE)
+ assert "LangSmith Gateway HTTP 424" in result and "no Google key" in result