Add a direct image generation API with `ImageGenerator`

Merged
EG
25d ago
+60785-724

This pull request was posted by Claude Code using claude-fable-5-1 on behalf of David.

Why we make these changes

Dedicated image models don't fit the conversational Model request/response path, so today they are only reachable through an agent run and the subagent tool it spins up; #3898 asks for a direct primitive. This adds pydantic_ai.images: an ImageGenerator facade over an ImageGenerationModel ABC with adapters for OpenAI, Google (Gemini Developer API and Vertex AI) and xAI, an ImageGenerationSettings of four portable keys that each provider extends with prefixed ones, OpenTelemetry instrumentation shaped like the Embedder sibling, a direct route on the ImageGeneration capability so an agent tool can call a dedicated image model instead of a subagent, and a guide at docs/image-generation.md beside the API, capability and provider pages.

New public surface

ImageGenerator, ImageGenerationModel, ImageGenerationSettings, ImageGenerationResult and GeneratedImage at pydantic_ai, the same cut as embeddings; the value types and building blocks under pydantic_ai.images; one Model/Settings pair per provider under pydantic_ai.images.openai / .google / .xai; native_tools.ImageSize; and on ImageGeneration, new fallback_image_model and dimensions arguments, a local that also takes an ImageGenerator, and a widened aspect_ratio.

Imports and where each symbol is used
from pydantic_ai import (
    GeneratedImage, ImageGenerationModel, ImageGenerationResult, ImageGenerationSettings, ImageGenerator,
)
from pydantic_ai.images import (
    ImageDimensions, ImageGenerationAspectRatio, ImageGenerationInput, InstrumentedImageGenerationModel,
    KnownImageGenerationModelName, TestImageGenerationModel, WrapperImageGenerationModel,
    infer_image_generation_model, instrument_image_generation_model, merge_image_generation_settings,
)
from pydantic_ai.images.openai import (
    OpenAIImageGenerationModel, OpenAIImageGenerationSettings, OpenAIImageOutputFormat,
)
# GoogleImageGenerationModel/Settings and XaiImageGenerationModel/Settings mirror this pair in .google and .xai
from pydantic_ai.capabilities import ImageGeneration
from pydantic_ai.native_tools import ImageSize

# Direct API
generator = ImageGenerator(
    'openai:gpt-image-2',  # KnownImageGenerationModelName | str | ImageGenerationModel; google-cloud: and gateway/google: reach Vertex AI
    settings=OpenAIImageGenerationSettings(openai_quality='low'),  # provider keys stay prefixed
    instrument=True,  # wraps the model in InstrumentedImageGenerationModel (a WrapperImageGenerationModel)
)
result: ImageGenerationResult = await generator.generate(
    'A watercolor map of a floating city.',
    images=[reference],  # Sequence[ImageGenerationInput]: BinaryImage | ImageUrl | UploadedFile; routes to the edit path
    settings=ImageGenerationSettings(dimensions=(1024, 1024)),  # ImageDimensions, or aspect_ratio: ImageGenerationAspectRatio
)
result.image  # BinaryImage, the first generated image
image: GeneratedImage = result.images[0]  # the batch, with per-image metadata
result.usage, result.cost(), result.provider_details

# Building blocks
model: ImageGenerationModel = infer_image_generation_model('google:gemini-3.1-flash-image')
model = OpenAIImageGenerationModel('gpt-image-2', provider=OpenAIProvider(base_url=...))
instrument_image_generation_model(model, True)
merge_image_generation_settings(generator_defaults, per_call_overrides)
with generator.override(model=TestImageGenerationModel()):
    ...

# Agent capability
ImageGeneration(fallback_image_model='openai:gpt-image-2', dimensions=(1024, 1024))  # or an ImageGenerationModel
ImageGeneration(native=False, local=ImageGenerator('openai:gpt-image-2'))  # a generator goes on `local`
ImageGeneration(size='1K')  # size: ImageSize, hoisted beside native_tools.ImageAspectRatio

User-visible behavior

from pydantic_ai import ImageGenerator

result = ImageGenerator('openai:gpt-image-2').generate_sync('A watercolor map of a floating city.')
image = result.image  # BinaryImage; result.images holds the batch with per-image metadata

dimensions, aspect_ratio, extra_headers and extra_body are the whole portable settings surface; everything else keeps a provider prefix, and a prefixed value wins over the portable one with a warning. images= routes the call to the provider's edit path, and a moderation block raises ContentFilterError — except on xAI, which moderates silently, so a partly flagged batch returns the clean images and lists the rest in result.provider_details['moderated_image_indices']. instrument=True emits an image_generation {model} span. google-cloud: and gateway/google: reach Vertex AI, where reference images are BinaryImage or ImageUrl only; gateway/openai: and gateway/xai: raise UserError because the gateway does not proxy those image endpoints.

Verification

  • tests/test_images.py: per-provider wire payloads, geometry and error mapping, with test_openai_image_generation_moderation_blocked and test_openai_empty_string_settings_are_forwarded driving the real SDK over a mock transport, plus recorded generate and edit calls for all three providers (test_openai_gpt_image_2_generation_vcr, test_openai_image_edit_vcr, test_google_image_generation_vcr, test_google_cloud_image_generation_vcr, test_google_cloud_image_edit_vcr, test_xai_image_generation_vcr, test_xai_image_generation_batch_vcr). The Gemini geometry tables follow the live API rather than Google's published tiers, pinned by test_google_flash_lite_extended_aspect_ratio_vcr and test_google_flash_21_9_512_dimensions_vcr, and an xAI batch billing one batch-wide cost rather than a per-image share is pinned by test_xai_image_generation_batch_vcr.
  • tests/test_capability_image_generation.py: the direct route on the capability, in test_image_generation_accepts_direct_image_model and test_image_generation_direct_fallback; which field takes which, in test_image_generation_accepts_a_generator_on_local, test_image_generation_rejects_a_generator_on_fallback_image_model, test_image_generation_rejects_a_bare_image_model_on_local and test_image_generation_rejects_more_than_one_fallback; a replaced or merged capability sending its own settings, in test_image_generation_replace_sends_the_replaced_dimensions, test_image_generation_composed_capabilities_send_the_merged_dimensions and test_image_generation_merged_dimensions_take_the_later_pair; and the content-filter conversion over both fallbacks, in test_image_generation_content_filter_error_becomes_model_retry.
  • tests/durable_exec/temporal/test_durability.py::test_durability_image_generation_capability_runs_in_activity drives a worker end to end — the generator asserts it is inside an activity and its BinaryImage comes back as the tool-result payload — and tests/test_examples.py runs the new docs examples without provider credentials.

What changes for existing users

Nothing on the Agent/Model path, and nothing on the ImageGeneration(fallback_subagent_model=...) subagent path except that the Grok Imagine family (grok-imagine-image and its aliases) is now rejected at construction with the same UserError as dall-e-2/dall-e-3, whose message additionally points at fallback_image_model. Content-filter handling on that path is unchanged: ContentFilterError subclasses UnexpectedModelBehavior, which the subagent tool already converted to ModelRetry on main. The xai extra's floor moves to xai-sdk>=1.16.0, for the image_file_id/image_file_ids arguments the edit path needs.

Design decisions

Thirteen decisions settled during review — each is permanent for the rest of v2 and would take a public API change to undo
  1. Image-only type set. ImageGenerator, ImageGenerationModel and ImageGenerationSettings are image-specific, with no shared base spanning image, video and audio. This supersedes the ask for a single type set across all three in #3898; the later planning call that settled on image-only has no public record, so this PR is that record.

  2. Four portable settings: dimensions, aspect_ratio, extra_headers, extra_body. Everything else carries a provider prefix, a prefixed value wins over the portable one, and the conflict warns rather than raising. The provider stays the authority on what it accepts today: Google forwards a ratio unvalidated, OpenAI maps it onto its model family's enumerated sizes and raises UserError outside that set, and xAI raises UserError for the seven portable ratios its xai_sdk ImageAspectRatio enum has no member for — 1:4, 1:8, 4:1, 4:5, 5:4, 8:1 and 21:9 — which the gRPC request therefore cannot carry. This departs from the client-side validation asked for on #3720 (comment): live probes showed those tables go stale (Gemini accepts 1:8 at 1K where the table rejected it), so the provider is the authority and the error, when there is one, is the provider's.

  3. Root exports are five symbols. pydantic_ai exports ImageGenerator, ImageGenerationModel, ImageGenerationSettings, ImageGenerationResult and GeneratedImage. ImageDimensions, ImageGenerationAspectRatio and ImageGenerationInput stay in pydantic_ai.images, and OpenAIImageOutputFormat sits in pydantic_ai.images.openai next to the openai_output_format field it types. The cut copies the embeddings one — facade, ABC, settings, result — plus GeneratedImage, which ImageGenerationResult.images is made of; promoting a symbol later is free, demoting one is a break.

  4. Geometry tables follow the live API, not the published docs. Gemini 3.1's extended ratios are enumerated as the API actually returns them — 1:8 at 1K is 352x2928 where Google publishes 384x3072 — OpenAI's fixed-size table is frozen to the GPT Image 1.x family so an unknown model name forwards exact dimensions for OpenAI itself to validate, and dall-e-2/dall-e-3 raise UserError at construction. dimensions promises an exact output shape, so the table has to match what the provider returns rather than what it documents.

  5. xAI returns the clean subset of a partially moderated batch. Flagged slots are skipped and their positions reported on result.provider_details['moderated_image_indices']; ContentFilterError is raised only when every slot was flagged. xAI moderates silently on an otherwise successful RPC, so failing the whole batch would discard clean images the caller already paid for.

  6. A content block is a ContentFilterError on the direct API and a ModelRetry on both capability fallbacks. ImageGenerator.generate raises it; inside ImageGeneration, the fallback_subagent_model subagent and the new direct tool both convert it — the direct tool the same way whether local's generator or fallback_image_model built it — so no capability tool lets it escape: a durable engine matches non-retryable errors by class name, and ContentFilterError is not on that list, so an escape would leave the tool activity retrying a deterministic refusal.

  7. gen_ai.operation.name is 'image_generation' and the span is image_generation {model}. The OpenTelemetry GenAI conventions enumerate no value for image generation and explicitly allow a custom one, and generate_content would make image spans indistinguishable from Gemini chat spans.

  8. The facade mirrors Embedder. ImageGenerator(model, *, settings, defer_model_check=True, instrument=None) with instrument_all() and override(model=...), and infer_image_generation_model accepting openai:, google:, google-cloud:, xai: and gateway/google: while rejecting gateway/openai: and gateway/xai: with a UserError naming the supported route. Three departures from the sibling are deliberate: ImageGenerator compares by identity (eq=False), because instrument is its only dataclass field, so generated field equality would call two generators over different models equal — and merging two ImageGeneration capabilities under one id would keep the first where every other scalar field takes the later one; InstrumentedImageGenerationModel takes options keyword-only; and neither facade has a durable-execution wrapper, so a generator called from workflow code runs inline (#8026). Embedder is released, so it keeps its field equality (#8144).

  9. The result surface: image is unguarded, provider_details is dict[str, Any], and cost() can raise. .image returns images[0].content with no empty check, held up by the ImageGenerationModel.generate contract that an implementation with nothing to return raises instead of returning an empty result. GeneratedImage carries no provider image id — no adapter had one to populate. cost() prices through genai-prices, so the GPT Image and Gemini image families resolve and the Grok Imagine family raises LookupError, having no entry in the pricing data and no unit that counts generated images to price it with.

  10. Every result is materialized bytes. GeneratedImage.content is a BinaryImage; the xAI request pins image_format='base64' and the OpenAI adapter requires b64_json on every returned image, so a provider-hosted image URL is never surfaced. Adding URLs later would be additive, but the commitment that a result always carries bytes is made now.

  11. Google is asked for image-only output. The request sends response_modalities=['IMAGE'], so any text the model would have returned alongside the image is discarded rather than surfaced on the result.

  12. An unapplied setting is a UserWarning, not an error. Ignored and overridden settings warn from the adapter frame, which is the only frame always worth naming — ImageGenerator and any number of WrapperImageGenerationModel layers can sit between it and user code. Under a suite running filterwarnings = error that warning is an exception, so the warn-versus-raise choice is user-visible, not just a log line.

  13. The direct fallback splits across local and fallback_image_model, by what you hand over. An ImageGenerator carries settings of its own, so it is one of the local implementations local takes, beside the Tool, toolset and callable every NativeOrLocalTool accepts; the generate_image tool is derived from it where the toolset is built, so a replaced or merged capability never sends an earlier one's settings. fallback_image_model names a model, so it takes an ImageGenerationModel or a 'provider:model' string — the only form from_spec can carry from an agent spec. A name stays on the field and its generator is built by a cached_property, which is the shape combine knows to drop and recompute; wrapping it at construction would leave the field holding what it refuses to be given, since dataclasses.replace feeds every field back through __post_init__. Each field rejects the other's type with an error naming the right one, and at most one of local, fallback_subagent_model and fallback_image_model may be set. A local string still raises: on the base class it is a named local strategy (WebSearch(local='duckduckgo')), which a remote model id is not. NativeOrLocalTool._has_local_fallback() is a new subclass hook, defaulting to today's self.local is not None, which ImageGeneration overrides to read fallback_image_model too, so native=False beside a bare model name is not read as the silent no-op capability __post_init__ rejects. The field name mirrors fallback_subagent_model, the name #8077 gave the subagent field on main and this branch now carries: fallback says the model is reached only when the agent's model has no native support, and image model says a dedicated image model runs where the other runs a conversational one in a subagent. image_model stays the native tool's own model name and stays unprefixed, so the two are told apart by the provider prefix — the same confusion model was renamed for on #5234 (comment).

Overlapping open PRs

#7807 (provider-specific native-tool fields onto provider_settings) and #6754 (multimodal Embedder inputs) rewrite the same ImageGeneration field block, native_tools/__init__.py, embeddings/ and root __init__.py lines this PR touches, and both rebase onto this one; #8077 and #7541 have merged and are integrated here.

Checklist

  • Any AI generated code has been reviewed line-by-line by the human PR author, who stands by it.
  • No breaking changes in accordance with the version policy.
  • Any permitted compatibility impact has a label, warning, migration, release note, and exact API-check waiver.
  • PR title is fit for the release changelog.