pydantic_ai.images
Bases: ImageGenerationModel
Base class for image generation models that wrap another model.
Use this as a base class to create custom image generation model wrappers that modify behavior (e.g., caching, logging, rate limiting) while delegating to an underlying model.
By default, all methods are passed through to the wrapped model. Override specific methods to customize behavior.
The underlying image generation model being wrapped.
Type: ImageGenerationModel Default: infer_image_generation_model(wrapped) if isinstance(wrapped, str) else wrapped
Get the settings from the wrapped image generation model.
Type: ImageGenerationSettings | None
def __init__(wrapped: ImageGenerationModel | str)
Initialize the wrapper with an image generation model.
wrapped : ImageGenerationModel | str
The model to wrap. Can be an
ImageGenerationModel instance
or a model name string (e.g., 'openai:gpt-image-1').
One generated image with normalized content and provider metadata.
The generated image as normalized binary content.
Type: BinaryImage
Provider-revised or enhanced prompt, if available.
Type: str | None Default: None
Generated image output format, derived from the bytes the provider returned.
Type: str | None Default: None
Provider-specific details for this generated image.
Type: dict[str, Any] | None Default: None
Bases: ABC
Abstract base class for image generation models.
Get the default settings for this model.
Type: ImageGenerationSettings | None
The base URL for the provider API, if available.
The name of the image generation model.
Type: str
The image generation model provider/system identifier.
Type: str
def __init__(*, settings: ImageGenerationSettings | None = None) -> None
Initialize the model with optional settings.
settings : ImageGenerationSettings | None Default: None
Model-specific settings that will be used as defaults for this model.
@abstractmethod
@async
def generate(
prompt: str,
*,
images: Sequence[ImageGenerationInput] | None = None,
settings: ImageGenerationSettings | None = None,
) -> ImageGenerationResult
Generate images for the given prompt.
The result always holds at least one image. An implementation with no image to return raises
ContentFilterError when the provider blocked the output, and
UnexpectedModelBehavior otherwise, rather than returning an
empty result.
def prepare_generate(
prompt: str,
*,
images: Sequence[ImageGenerationInput] | None = None,
settings: ImageGenerationSettings | None = None,
) -> tuple[str, list[ImageGenerationInput], ImageGenerationSettings]
Prepare the prompt, reference images, and settings for image generation.
tuple[str, list[ImageGenerationInput], ImageGenerationSettings]
Bases: ImageGenerationModel
A deterministic image generation model for testing.
This model returns a single 1x1 PNG without making any API calls, and records the reference images
and settings used in the last call via the last_images and last_settings attributes.
Example:
from pydantic_ai import ImageGenerator
from pydantic_ai.images import TestImageGenerationModel
test_model = TestImageGenerationModel()
generator = ImageGenerator('openai:gpt-image-2')
async def main():
with generator.override(model=test_model):
await generator.generate('A test image', settings={'aspect_ratio': '16:9'})
print(test_model.last_settings)
#> {'aspect_ratio': '16:9'}
print(test_model.last_images)
#> []
The reference images passed to the most recent generate call.
Type: list[ImageGenerationInput] Default: []
The settings used in the most recent generate call.
Type: ImageGenerationSettings | None Default: None
The image generation model name.
Type: str
The image generation model provider.
Type: str
def __init__(
model_name: str = 'test',
*,
provider_name: str = 'test',
settings: ImageGenerationSettings | None = None,
)
Initialize the test image generation model.
model_name : str Default: 'test'
The model name to report in results.
provider_name : str Default: 'test'
The provider name to report in results.
settings : ImageGenerationSettings | None Default: None
Optional default settings for the model.
The result of an image generation operation.
Generated images.
Type: Sequence[GeneratedImage]
The input prompt used for generation.
Type: str
The name of the model that generated the images.
Type: str
The name of the provider.
Type: str
When the image generation request was made.
Type: datetime Default: field(default_factory=_now_utc)
Usage statistics for this request.
Type: RequestUsage Default: field(default_factory=RequestUsage)
Provider-specific details from the response.
Type: dict[str, Any] | None Default: None
Unique identifier for this response from the provider, if available.
Type: str | None Default: None
Provider API URL, if available.
Type: str | None Default: None
The first generated image. Use images when the request asked for more than one.
A result always holds at least one image: the
ImageGenerationModel.generate contract
requires an implementation with nothing to return to raise instead of returning an empty result.
Type: BinaryImage
def cost() -> genai_types.PriceCalculation
Calculate the cost of the image generation request.
Uses genai-prices for pricing data.
Models priced per token are covered, such as the GPT Image and Gemini image families. The
Grok Imagine family raises LookupError: it has no entry in the pricing data, and there is
no unit that counts generated images to price it with.
genai_types.PriceCalculation — A price calculation object with total_price, input_price, and other cost details.
LookupError— If pricing data is not available for this model/provider.
Bases: WrapperImageGenerationModel
Image generation model which wraps another model for OpenTelemetry instrumentation.
Instrumentation settings for this model.
Type: InstrumentationSettings Default: options or InstrumentationSettings()
Bases: TypedDict
Normalized settings for configuring image generation models.
This type contains only settings with the same semantics across every direct image provider. Provider-specific settings classes extend it with prefixed options for controls that are not portable.
The exact output dimensions as (width, height) in pixels.
This is mutually exclusive with aspect_ratio. The selected provider and
model must support the exact dimensions;
no rounding or nearest-shape fallback is applied. GPT Image 1.x accepts its
three fixed shapes, GPT Image 2 validates a continuous constrained range, and
Gemini/Grok Imagine accept their model-specific aspect-ratio and resolution
table entries. See the ImageDimensions documentation for the full matrix.
Type: ImageDimensions
The requested aspect ratio.
Providers with a native aspect-ratio field receive the ratio as given, and reject
an unsupported one themselves. OpenAI has no such field, so Pydantic AI maps the
ratio to one of the model family’s enumerated sizes and raises UserError for a
ratio outside that set; xAI takes an enum with no member for some portable values
and raises UserError for those. See the
Image Generation guide
for the per-family shapes.
Type: ImageGenerationAspectRatio
Extra headers to send to the model.
This follows the existing ModelSettings and EmbeddingSettings escape-hatch pattern.
Prefer provider-prefixed typed settings when a setting is part of the supported public API.
Extra body to send to the model.
This follows the existing ModelSettings and EmbeddingSettings escape-hatch pattern.
Prefer provider-prefixed typed settings when a setting is part of the supported public API.
Type: object
High-level interface for generating images.
The ImageGenerator class provides a convenient way to generate images from a prompt, and to edit
or transform reference images, using dedicated image models. It handles model inference, settings
management, and optional OpenTelemetry instrumentation.
Example:
from pydantic_ai import ImageGenerator
generator = ImageGenerator('openai:gpt-image-2')
async def main():
result = await generator.generate('A watercolor map of a floating city.')
print(result.image.media_type)
#> image/png
Options to automatically instrument with OpenTelemetry.
Set to True to use default instrumentation settings, which will use Logfire if it’s configured.
Set to an instance of InstrumentationSettings
to customize. If this isn’t set, then the last value set by
ImageGenerator.instrument_all()
will be used, which defaults to False.
Type: InstrumentationSettings | bool | None Default: instrument
The image generation model used by this generator.
Type: ImageGenerationModel | KnownImageGenerationModelName | str
def __init__(
model: ImageGenerationModel | KnownImageGenerationModelName | str,
*,
settings: ImageGenerationSettings | None = None,
defer_model_check: bool = True,
instrument: InstrumentationSettings | bool | None = None,
) -> None
Initialize an ImageGenerator.
model : ImageGenerationModel | KnownImageGenerationModelName | str
The image generation model to use. Can be specified as:
- A model name string in the format
'provider:model-name'(e.g.,'openai:gpt-image-2') - An
ImageGenerationModelinstance
settings : ImageGenerationSettings | None Default: None
Optional ImageGenerationSettings
to use as defaults for all generate calls.
defer_model_check : bool Default: True
Whether to defer resolving the model name to a model instance, and the
provider authentication that resolution requires, until the first generate call.
Set to False to resolve the model immediately on construction.
instrument : InstrumentationSettings | bool | None Default: None
OpenTelemetry instrumentation settings. Set to True to enable with defaults,
or pass an InstrumentationSettings
instance to customize. If None, uses the value from
ImageGenerator.instrument_all().
@staticmethod
def instrument_all(instrument: InstrumentationSettings | bool = True) -> None
Set the default instrumentation options for all image generators where instrument is not explicitly set.
This is useful for enabling instrumentation globally without modifying each generator individually.
instrument : InstrumentationSettings | bool Default: True
Instrumentation settings to use as the default. Set to True for default settings,
False to disable, or pass an
InstrumentationSettings
instance to customize.
def override(
*,
model: ImageGenerationModel | KnownImageGenerationModelName | str | _utils.Unset = _utils.UNSET,
) -> Generator[None]
Context manager to temporarily override the image generation model.
Useful for testing or dynamically switching models.
Example:
from pydantic_ai import ImageGenerator
generator = ImageGenerator('openai:gpt-image-2')
async def main():
# Temporarily use a different model
with generator.override(model='google:gemini-3.1-flash-image'):
result = await generator.generate('A watercolor map of a floating city.')
print(result.model_name)
#> gemini-3.1-flash-image
model : ImageGenerationModel | KnownImageGenerationModelName | str | _utils.Unset Default: _utils.UNSET
The image generation model to use within this context.
@async
def generate(
prompt: str,
*,
images: Sequence[ImageGenerationInput] | None = None,
settings: ImageGenerationSettings | None = None,
) -> ImageGenerationResult
Generate images from a prompt and optional reference images.
ImageGenerationResult — An ImageGenerationResult containing the
ImageGenerationResult — generated images and metadata about the operation.
prompt : str
The text prompt describing the image to generate.
Optional reference images to edit or transform. Passing reference images sends the
request to the provider’s image-editing path, preserving the order of the images. Each
item can be a BinaryImage,
ImageUrl, or
UploadedFile; see the
Image Generation guide for the reference-input
types each provider accepts.
settings : ImageGenerationSettings | None Default: None
Optional settings to override the generator’s default settings for this call.
ContentFilterError— If the provider blocked the request, or every generated image, for content moderation.UserError— If the prompt is empty, a setting is invalid, or the model cannot produce the requested dimensions.
def generate_sync(
prompt: str,
*,
images: Sequence[ImageGenerationInput] | None = None,
settings: ImageGenerationSettings | None = None,
) -> ImageGenerationResult
Synchronous version of generate().
ImageGenerationResult — An ImageGenerationResult containing the
ImageGenerationResult — generated images and metadata about the operation.
prompt : str
The text prompt describing the image to generate.
Optional reference images to edit or transform.
settings : ImageGenerationSettings | None Default: None
Optional settings to override the generator’s default settings for this call.
ContentFilterError— If the provider blocked the request, or every generated image, for content moderation.UserError— If the prompt is empty, a setting is invalid, or the model cannot produce the requested dimensions.
def instrument_image_generation_model(
model: ImageGenerationModel,
instrument: InstrumentationSettings | bool,
) -> ImageGenerationModel
Instrument an image generation model with OpenTelemetry/logfire.
def infer_image_generation_model(
model: ImageGenerationModel | KnownImageGenerationModelName | str,
*,
provider_factory: Callable[[str], Provider[Any]] = infer_provider,
) -> ImageGenerationModel
Infer the image generation model from the name.
def merge_image_generation_settings(
base: ImageGenerationSettings | None,
overrides: ImageGenerationSettings | None,
) -> ImageGenerationSettings | None
Merge two sets of image generation settings, with overrides taking precedence.
ImageGenerationSettings | None
Exact output image dimensions as (width, height) in pixels.
Supported values are model-specific. GPT Image 1.x accepts three fixed shapes; GPT Image 2 accepts any shape satisfying its edge, area, multiple-of-16, and 3:1 limits; Gemini and Grok Imagine accept the documented or verified shapes for their aspect-ratio and resolution tiers. See the Image Generation guide for the complete matrix.
Type: TypeAlias Default: tuple[int, int]
An image input that can be used as a reference for image generation.
Default: TypeAliasType('ImageGenerationInput', ImageUrl | BinaryImage | UploadedFile)
Portable aspect ratios accepted by at least one direct image model adapter.
The canonical exact shape a ratio produces is model-family specific, and the
families name different subsets: GPT Image 1.x three, GPT Image 2 sixteen,
Gemini 2.5 Flash and Gemini 3 Pro ten, Gemini 3.1 Flash and Flash Lite fourteen,
and Grok Imagine thirteen. A ratio outside a family’s set still reaches Gemini,
which validates it itself; OpenAI and xAI have no way to carry it and raise
UserError. See the
Image Generation guide
for the ratio-to-dimensions matrix.
This is the direct image API’s vocabulary. The native image generation tool takes
ImageAspectRatio instead, whose ten
values are a subset of these twenty.
Type: TypeAlias Default: Literal['1:1', '1:2', '1:4', '1:8', '2:1', '2:3', '3:2', '3:4', '4:1', '4:3', '4:5', '5:4', '8:1', '9:16', '9:19.5', '9:20', '16:9', '19.5:9', '20:9', '21:9']
Known model names that can be used with the model parameter of ImageGenerator.
google: is the Gemini Developer API (Google AI Studio) and google-cloud: is Vertex AI, exactly as
in KnownModelName. A Pydantic AI Gateway route
is also accepted for Gemini as gateway/google:<model>.
Default: TypeAliasType('KnownImageGenerationModelName', Literal['google-cloud:gemini-2.5-flash-image', 'google-cloud:gemini-3-pro-image', 'google-cloud:gemini-3.1-flash-image', 'google-cloud:gemini-3.1-flash-lite-image', 'google:gemini-2.5-flash-image', 'google:gemini-3-pro-image', 'google:gemini-3.1-flash-image', 'google:gemini-3.1-flash-lite-image', 'openai:gpt-image-1', 'openai:gpt-image-1-mini', 'openai:gpt-image-1.5', 'openai:gpt-image-2', 'xai:grok-imagine-image', 'xai:grok-imagine-image-2.0', 'xai:grok-imagine-image-quality'])
Bases: ABC
Abstract base class for image generation models.
Get the default settings for this model.
Type: ImageGenerationSettings | None
The base URL for the provider API, if available.
The name of the image generation model.
Type: str
The image generation model provider/system identifier.
Type: str
def __init__(*, settings: ImageGenerationSettings | None = None) -> None
Initialize the model with optional settings.
settings : ImageGenerationSettings | None Default: None
Model-specific settings that will be used as defaults for this model.
@abstractmethod
@async
def generate(
prompt: str,
*,
images: Sequence[ImageGenerationInput] | None = None,
settings: ImageGenerationSettings | None = None,
) -> ImageGenerationResult
Generate images for the given prompt.
The result always holds at least one image. An implementation with no image to return raises
ContentFilterError when the provider blocked the output, and
UnexpectedModelBehavior otherwise, rather than returning an
empty result.
def prepare_generate(
prompt: str,
*,
images: Sequence[ImageGenerationInput] | None = None,
settings: ImageGenerationSettings | None = None,
) -> tuple[str, list[ImageGenerationInput], ImageGenerationSettings]
Prepare the prompt, reference images, and settings for image generation.
tuple[str, list[ImageGenerationInput], ImageGenerationSettings]
An image input that can be used as a reference for image generation.
Default: TypeAliasType('ImageGenerationInput', ImageUrl | BinaryImage | UploadedFile)
One generated image with normalized content and provider metadata.
The generated image as normalized binary content.
Type: BinaryImage
Provider-revised or enhanced prompt, if available.
Type: str | None Default: None
Generated image output format, derived from the bytes the provider returned.
Type: str | None Default: None
Provider-specific details for this generated image.
Type: dict[str, Any] | None Default: None
The result of an image generation operation.
Generated images.
Type: Sequence[GeneratedImage]
The input prompt used for generation.
Type: str
The name of the model that generated the images.
Type: str
The name of the provider.
Type: str
When the image generation request was made.
Type: datetime Default: field(default_factory=_now_utc)
Usage statistics for this request.
Type: RequestUsage Default: field(default_factory=RequestUsage)
Provider-specific details from the response.
Type: dict[str, Any] | None Default: None
Unique identifier for this response from the provider, if available.
Type: str | None Default: None
Provider API URL, if available.
Type: str | None Default: None
The first generated image. Use images when the request asked for more than one.
A result always holds at least one image: the
ImageGenerationModel.generate contract
requires an implementation with nothing to return to raise instead of returning an empty result.
Type: BinaryImage
def cost() -> genai_types.PriceCalculation
Calculate the cost of the image generation request.
Uses genai-prices for pricing data.
Models priced per token are covered, such as the GPT Image and Gemini image families. The
Grok Imagine family raises LookupError: it has no entry in the pricing data, and there is
no unit that counts generated images to price it with.
genai_types.PriceCalculation — A price calculation object with total_price, input_price, and other cost details.
LookupError— If pricing data is not available for this model/provider.
Bases: TypedDict
Normalized settings for configuring image generation models.
This type contains only settings with the same semantics across every direct image provider. Provider-specific settings classes extend it with prefixed options for controls that are not portable.
The exact output dimensions as (width, height) in pixels.
This is mutually exclusive with aspect_ratio. The selected provider and
model must support the exact dimensions;
no rounding or nearest-shape fallback is applied. GPT Image 1.x accepts its
three fixed shapes, GPT Image 2 validates a continuous constrained range, and
Gemini/Grok Imagine accept their model-specific aspect-ratio and resolution
table entries. See the ImageDimensions documentation for the full matrix.
Type: ImageDimensions
The requested aspect ratio.
Providers with a native aspect-ratio field receive the ratio as given, and reject
an unsupported one themselves. OpenAI has no such field, so Pydantic AI maps the
ratio to one of the model family’s enumerated sizes and raises UserError for a
ratio outside that set; xAI takes an enum with no member for some portable values
and raises UserError for those. See the
Image Generation guide
for the per-family shapes.
Type: ImageGenerationAspectRatio
Extra headers to send to the model.
This follows the existing ModelSettings and EmbeddingSettings escape-hatch pattern.
Prefer provider-prefixed typed settings when a setting is part of the supported public API.
Extra body to send to the model.
This follows the existing ModelSettings and EmbeddingSettings escape-hatch pattern.
Prefer provider-prefixed typed settings when a setting is part of the supported public API.
Type: object
def merge_image_generation_settings(
base: ImageGenerationSettings | None,
overrides: ImageGenerationSettings | None,
) -> ImageGenerationSettings | None
Merge two sets of image generation settings, with overrides taking precedence.
ImageGenerationSettings | None
Exact output image dimensions as (width, height) in pixels.
Supported values are model-specific. GPT Image 1.x accepts three fixed shapes; GPT Image 2 accepts any shape satisfying its edge, area, multiple-of-16, and 3:1 limits; Gemini and Grok Imagine accept the documented or verified shapes for their aspect-ratio and resolution tiers. See the Image Generation guide for the complete matrix.
Type: TypeAlias Default: tuple[int, int]
Portable aspect ratios accepted by at least one direct image model adapter.
The canonical exact shape a ratio produces is model-family specific, and the
families name different subsets: GPT Image 1.x three, GPT Image 2 sixteen,
Gemini 2.5 Flash and Gemini 3 Pro ten, Gemini 3.1 Flash and Flash Lite fourteen,
and Grok Imagine thirteen. A ratio outside a family’s set still reaches Gemini,
which validates it itself; OpenAI and xAI have no way to carry it and raise
UserError. See the
Image Generation guide
for the ratio-to-dimensions matrix.
This is the direct image API’s vocabulary. The native image generation tool takes
ImageAspectRatio instead, whose ten
values are a subset of these twenty.
Type: TypeAlias Default: Literal['1:1', '1:2', '1:4', '1:8', '2:1', '2:3', '3:2', '3:4', '4:1', '4:3', '4:5', '5:4', '8:1', '9:16', '9:19.5', '9:20', '16:9', '19.5:9', '20:9', '21:9']
Bases: ImageGenerationSettings
Settings used for an OpenAI image generation request.
All fields from ImageGenerationSettings
are supported, plus OpenAI-specific settings prefixed with openai_.
The number of images to generate.
Type: int
The generated image format.
Type: OpenAIImageOutputFormat
OpenAI image size setting.
This is provider-specific because OpenAI, Gemini, xAI, and other image APIs use different concepts for pixel sizes, aspect ratios, and resolution tiers.
Type: str
GPT Image quality setting.
Type: Literal[‘low’, ‘medium’, ‘high’, ‘auto’]
OpenAI image background setting.
Type: Literal[‘transparent’, ‘opaque’, ‘auto’]
OpenAI input fidelity setting for image editing.
Type: Literal[‘high’, ‘low’]
OpenAI moderation strictness for image generation.
Type: Literal[‘auto’, ‘low’]
OpenAI output compression setting.
Type: int
OpenAI end-user identifier.
Type: str
Bases: ImageGenerationModel
OpenAI image generation model implementation.
This model works with OpenAI’s Images API and the GPT Image model family, such as gpt-image-2,
gpt-image-1.5, gpt-image-1, and gpt-image-1-mini.
The dall-e-2 and dall-e-3 models are not supported and raise a
UserError on construction, even though they are part of the
OpenAI SDK’s ImageModel type: they diverge from the GPT Image request and response contract in
size, quality, image count, and response format. Unrecognized model names are passed through to
OpenAI, so newly released GPT Image models work without a Pydantic AI release.
Example:
from pydantic_ai.images.openai import OpenAIImageGenerationModel
from pydantic_ai.providers.openai import OpenAIProvider
# Using OpenAI directly
model = OpenAIImageGenerationModel('gpt-image-2')
# Using a custom base URL or client configuration
model = OpenAIImageGenerationModel(
'gpt-image-2',
provider=OpenAIProvider(base_url='https://my-provider.com/v1'),
)
The image generation model name.
Type: OpenAIImageGenerationModelName
The image generation model provider.
Type: str
def __init__(
model_name: OpenAIImageGenerationModelName,
*,
provider: Literal['openai'] | Provider[AsyncOpenAI] = 'openai',
settings: ImageGenerationSettings | None = None,
)
Initialize an OpenAI image generation model.
The name of the GPT Image model to use. See OpenAI’s image generation guide for available models.
provider : Literal[‘openai’] | Provider[AsyncOpenAI] Default: 'openai'
The provider to use for authentication and API access. Can be:
'openai'(default): Uses the standard OpenAI API- A
Providerinstance for custom configuration, such as anOpenAIProviderwith a custombase_urloropenai_client
settings : ImageGenerationSettings | None Default: None
Model-specific
ImageGenerationSettings
to use as defaults for this model.
UserError— Ifmodel_nameis a DALL·E model, which this adapter does not support.
Possible OpenAI image generation model names.
Default: str | LatestOpenAIImageModelNames
The image formats OpenAI’s image endpoints accept as a requested output format.
This types the openai_output_format request setting. It does not describe
GeneratedImage.output_format, which is a plain str | None
derived from the media type each adapter resolves for the bytes the provider returned.
Default: Literal['png', 'webp', 'jpeg']
Bases: ImageGenerationSettings
Settings used for a Google image generation request.
All fields from ImageGenerationSettings
are supported, plus Google-specific settings prefixed with google_.
Google image generation configuration, including aspect ratio and image size.
Type: ImageConfigDict
Bases: ImageGenerationModel
Google Gemini image generation model implementation.
This model works with the Gemini image models, such as gemini-3.1-flash-image and
gemini-3-pro-image, through the Gemini Developer API (Google AI Studio) or Google Cloud
(Vertex AI). It asks Gemini for an image-only response, as
ImageGenerator returns generated images rather than
Gemini’s optional conversational text.
Example:
from pydantic_ai.images.google import GoogleImageGenerationModel
from pydantic_ai.providers.google import GoogleProvider
from pydantic_ai.providers.google_cloud import GoogleCloudProvider
# Using the Gemini API (requires GOOGLE_API_KEY env var)
model = GoogleImageGenerationModel('gemini-3.1-flash-image')
# Or with explicit provider configuration
model = GoogleImageGenerationModel(
'gemini-3.1-flash-image',
provider=GoogleProvider(api_key='your-api-key'),
)
# Using Google Cloud (Vertex AI)
model = GoogleImageGenerationModel(
'gemini-3.1-flash-image',
provider=GoogleCloudProvider(project='my-project', location='global'),
)
The image generation model name.
Type: GoogleImageGenerationModelName
The image generation model provider.
Type: str
def __init__(
model_name: GoogleImageGenerationModelName,
*,
provider: Literal['google', 'google-cloud'] | Provider[Client] = 'google',
settings: ImageGenerationSettings | None = None,
)
Initialize a Google image generation model.
The name of the Gemini image model to use. See Google’s image generation documentation for available models.
provider : Literal[‘google’, ‘google-cloud’] | Provider[Client] Default: 'google'
The provider to use for authentication and API access. Can be:
'google'(default): Uses the Gemini Developer API (Google AI Studio)'google-cloud': Uses Google Cloud (formerly known as Vertex AI)- A
GoogleProviderorGoogleCloudProviderinstance for custom configuration
settings : ImageGenerationSettings | None Default: None
Model-specific
ImageGenerationSettings
to use as defaults for this model.
Latest Gemini image generation models, served identically by the Gemini API and Google Cloud (Vertex AI).
See the Gemini image generation documentation for available models and their capabilities.
Default: Literal['gemini-2.5-flash-image', 'gemini-3-pro-image', 'gemini-3.1-flash-image', 'gemini-3.1-flash-lite-image']
Possible Google image generation model names.
Default: str | LatestGoogleImageGenerationModelNames
Bases: ImageGenerationSettings
Settings used for an xAI image generation request.
All fields from ImageGenerationSettings
are supported, plus xAI-specific settings prefixed with xai_.
The number of images to generate.
Type: int
A unique identifier representing your end-user.
Type: str
The aspect ratio of the generated image.
Type: XaiImageAspectRatio
The resolution tier of the generated image.
Type: ImageResolution
Bases: ImageGenerationModel
xAI image generation model implementation.
This model works with the Grok Imagine models, such as grok-imagine-image and
grok-imagine-image-quality, through the official xAI SDK, which connects over gRPC.
xAI moderates silently: a flagged image in a batch comes back empty rather than as an error, so the
clean images are returned and the flagged positions are reported through
provider_details['moderated_image_indices']. A
ContentFilterError is raised only when every image
was flagged. See the xAI model page for details.
Example:
from pydantic_ai.images.xai import XaiImageGenerationModel
from pydantic_ai.providers.xai import XaiProvider
# Using xAI directly (requires XAI_API_KEY env var)
model = XaiImageGenerationModel('grok-imagine-image')
# Or with explicit provider configuration
model = XaiImageGenerationModel(
'grok-imagine-image',
provider=XaiProvider(api_key='your-api-key'),
)
The image generation model name.
Type: XaiImageGenerationModelName
The image generation model provider.
Type: str
def __init__(
model_name: XaiImageGenerationModelName,
*,
provider: Literal['xai'] | Provider[AsyncClient] = 'xai',
settings: ImageGenerationSettings | None = None,
)
Initialize an xAI image generation model.
The name of the Grok Imagine model to use. See xAI’s image generation documentation for available models.
provider : Literal[‘xai’] | Provider[AsyncClient] Default: 'xai'
The provider to use for authentication and API access. Can be:
'xai'(default): Uses the standard xAI API- An
XaiProviderinstance for custom configuration, such as a customapi_hostorxai_client
settings : ImageGenerationSettings | None Default: None
Model-specific
ImageGenerationSettings
to use as defaults for this model.
Possible xAI image generation model names.
Default: str | LatestXaiImageGenerationModelNames
Bases: ImageGenerationModel
A deterministic image generation model for testing.
This model returns a single 1x1 PNG without making any API calls, and records the reference images
and settings used in the last call via the last_images and last_settings attributes.
Example:
from pydantic_ai import ImageGenerator
from pydantic_ai.images import TestImageGenerationModel
test_model = TestImageGenerationModel()
generator = ImageGenerator('openai:gpt-image-2')
async def main():
with generator.override(model=test_model):
await generator.generate('A test image', settings={'aspect_ratio': '16:9'})
print(test_model.last_settings)
#> {'aspect_ratio': '16:9'}
print(test_model.last_images)
#> []
The reference images passed to the most recent generate call.
Type: list[ImageGenerationInput] Default: []
The settings used in the most recent generate call.
Type: ImageGenerationSettings | None Default: None
The image generation model name.
Type: str
The image generation model provider.
Type: str
def __init__(
model_name: str = 'test',
*,
provider_name: str = 'test',
settings: ImageGenerationSettings | None = None,
)
Initialize the test image generation model.
model_name : str Default: 'test'
The model name to report in results.
provider_name : str Default: 'test'
The provider name to report in results.
settings : ImageGenerationSettings | None Default: None
Optional default settings for the model.
Bases: ImageGenerationModel
Base class for image generation models that wrap another model.
Use this as a base class to create custom image generation model wrappers that modify behavior (e.g., caching, logging, rate limiting) while delegating to an underlying model.
By default, all methods are passed through to the wrapped model. Override specific methods to customize behavior.
The underlying image generation model being wrapped.
Type: ImageGenerationModel Default: infer_image_generation_model(wrapped) if isinstance(wrapped, str) else wrapped
Get the settings from the wrapped image generation model.
Type: ImageGenerationSettings | None
def __init__(wrapped: ImageGenerationModel | str)
Initialize the wrapper with an image generation model.
wrapped : ImageGenerationModel | str
The model to wrap. Can be an
ImageGenerationModel instance
or a model name string (e.g., 'openai:gpt-image-1').
Bases: WrapperImageGenerationModel
Image generation model which wraps another model for OpenTelemetry instrumentation.
Instrumentation settings for this model.
Type: InstrumentationSettings Default: options or InstrumentationSettings()
def instrument_image_generation_model(
model: ImageGenerationModel,
instrument: InstrumentationSettings | bool,
) -> ImageGenerationModel
Instrument an image generation model with OpenTelemetry/logfire.