Add a direct image generation API with `ImageGenerator`
This pull request was posted by Claude Code using claude-fable-5-1 on behalf of David.
- Refs #3898
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, withtest_openai_image_generation_moderation_blockedandtest_openai_empty_string_settings_are_forwardeddriving 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 bytest_google_flash_lite_extended_aspect_ratio_vcrandtest_google_flash_21_9_512_dimensions_vcr, and an xAI batch billing one batch-wide cost rather than a per-image share is pinned bytest_xai_image_generation_batch_vcr.tests/test_capability_image_generation.py: the direct route on the capability, intest_image_generation_accepts_direct_image_modelandtest_image_generation_direct_fallback; which field takes which, intest_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_localandtest_image_generation_rejects_more_than_one_fallback; a replaced or merged capability sending its own settings, intest_image_generation_replace_sends_the_replaced_dimensions,test_image_generation_composed_capabilities_send_the_merged_dimensionsandtest_image_generation_merged_dimensions_take_the_later_pair; and the content-filter conversion over both fallbacks, intest_image_generation_content_filter_error_becomes_model_retry.tests/durable_exec/temporal/test_durability.py::test_durability_image_generation_capability_runs_in_activitydrives a worker end to end — the generator asserts it is inside an activity and itsBinaryImagecomes back as the tool-result payload — andtests/test_examples.pyruns 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
-
Image-only type set.
ImageGenerator,ImageGenerationModelandImageGenerationSettingsare 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. -
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 raisesUserErroroutside that set, and xAI raisesUserErrorfor the seven portable ratios itsxai_sdkImageAspectRatioenum has no member for —1:4,1:8,4:1,4:5,5:4,8:1and21: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 accepts1:8at1Kwhere the table rejected it), so the provider is the authority and the error, when there is one, is the provider's. -
Root exports are five symbols.
pydantic_aiexportsImageGenerator,ImageGenerationModel,ImageGenerationSettings,ImageGenerationResultandGeneratedImage.ImageDimensions,ImageGenerationAspectRatioandImageGenerationInputstay inpydantic_ai.images, andOpenAIImageOutputFormatsits inpydantic_ai.images.openainext to theopenai_output_formatfield it types. The cut copies the embeddings one — facade, ABC, settings, result — plusGeneratedImage, whichImageGenerationResult.imagesis made of; promoting a symbol later is free, demoting one is a break. -
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
1Kis 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, anddall-e-2/dall-e-3raiseUserErrorat construction.dimensionspromises an exact output shape, so the table has to match what the provider returns rather than what it documents. -
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'];ContentFilterErroris 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. -
A content block is a
ContentFilterErroron the direct API and aModelRetryon both capability fallbacks.ImageGenerator.generateraises it; insideImageGeneration, thefallback_subagent_modelsubagent and the new direct tool both convert it — the direct tool the same way whetherlocal's generator orfallback_image_modelbuilt it — so no capability tool lets it escape: a durable engine matches non-retryable errors by class name, andContentFilterErroris not on that list, so an escape would leave the tool activity retrying a deterministic refusal. -
gen_ai.operation.nameis'image_generation'and the span isimage_generation {model}. The OpenTelemetry GenAI conventions enumerate no value for image generation and explicitly allow a custom one, andgenerate_contentwould make image spans indistinguishable from Gemini chat spans. -
The facade mirrors
Embedder.ImageGenerator(model, *, settings, defer_model_check=True, instrument=None)withinstrument_all()andoverride(model=...), andinfer_image_generation_modelacceptingopenai:,google:,google-cloud:,xai:andgateway/google:while rejectinggateway/openai:andgateway/xai:with aUserErrornaming the supported route. Three departures from the sibling are deliberate:ImageGeneratorcompares by identity (eq=False), becauseinstrumentis its only dataclass field, so generated field equality would call two generators over different models equal — and merging twoImageGenerationcapabilities under one id would keep the first where every other scalar field takes the later one;InstrumentedImageGenerationModeltakesoptionskeyword-only; and neither facade has a durable-execution wrapper, so a generator called from workflow code runs inline (#8026).Embedderis released, so it keeps its field equality (#8144). -
The result surface:
imageis unguarded,provider_detailsisdict[str, Any], andcost()can raise..imagereturnsimages[0].contentwith no empty check, held up by theImageGenerationModel.generatecontract that an implementation with nothing to return raises instead of returning an empty result.GeneratedImagecarries 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 raisesLookupError, having no entry in the pricing data and no unit that counts generated images to price it with. -
Every result is materialized bytes.
GeneratedImage.contentis aBinaryImage; the xAI request pinsimage_format='base64'and the OpenAI adapter requiresb64_jsonon 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. -
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. -
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 —ImageGeneratorand any number ofWrapperImageGenerationModellayers can sit between it and user code. Under a suite runningfilterwarnings = errorthat warning is an exception, so the warn-versus-raise choice is user-visible, not just a log line. -
The direct fallback splits across
localandfallback_image_model, by what you hand over. AnImageGeneratorcarries settings of its own, so it is one of the local implementationslocaltakes, beside theTool, toolset and callable everyNativeOrLocalToolaccepts; thegenerate_imagetool is derived from it where the toolset is built, so a replaced or merged capability never sends an earlier one's settings.fallback_image_modelnames a model, so it takes anImageGenerationModelor a'provider:model'string — the only formfrom_speccan carry from an agent spec. A name stays on the field and its generator is built by acached_property, which is the shapecombineknows to drop and recompute; wrapping it at construction would leave the field holding what it refuses to be given, sincedataclasses.replacefeeds every field back through__post_init__. Each field rejects the other's type with an error naming the right one, and at most one oflocal,fallback_subagent_modelandfallback_image_modelmay be set. Alocalstring 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'sself.local is not None, whichImageGenerationoverrides to readfallback_image_modeltoo, sonative=Falsebeside a bare model name is not read as the silent no-op capability__post_init__rejects. The field name mirrorsfallback_subagent_model, the name #8077 gave the subagent field onmainand this branch now carries:fallbacksays the model is reached only when the agent's model has no native support, andimage modelsays a dedicated image model runs where the other runs a conversational one in a subagent.image_modelstays the native tool's own model name and stays unprefixed, so the two are told apart by the provider prefix — the same confusionmodelwas 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.