Skip to content

Convert Files

Convert images in a format the model rejects, such as HEIC, AVIF, BMP, TIFF, or GIF, into JPEG or PNG before each request, so the model reads the image itself instead of the request failing or the image being dropped. Use it on an agent that accepts photos or screenshots from users, or tools that return images, when the model behind it takes only a few image types.

While Pydantic AI Harness is on 0.x releases, the API may change between minor releases; when it does, deprecation warnings and release-note migration guidance tell you (or your agent) exactly how to upgrade. See the version policy.

flowchart TB
    accTitle: Convert Files: send each image in a type the model reads
    accDescr: A user prompt or tool result carries an image in a format the model's profile does not list. Before each model request, the ConvertFiles capability checks the image's media type against the profile's supported image media types. A listed type is sent as it is. An unlisted type is converted to JPEG or PNG, and the converted copy goes to the model while the message history keeps the original.
    source(["image in a prompt<br/>or tool result"])
    check{"media type in the<br/>model's profile?"}
    convert["ConvertFiles()<br/>HEIC, HEIF, AVIF to JPEG<br/>others to PNG"]:::capability
    model(["model request"])
    history["message history<br/>keeps the original"]
    source --> check
    check -->|"listed"| model
    check -->|"not listed"| convert
    convert -->|"converted copy"| model
    source --> history
    classDef capability stroke:#E520E9,stroke-width:2px

Usage

Install the convert-files extra, which includes Pillow and pillow-heif; without them, importing ConvertFiles raises an ImportError naming the extra.

Terminal
pip install "pydantic-ai-harness[convert-files]"
import io

from PIL import Image

from pydantic_ai import Agent, BinaryContent
from pydantic_ai.messages import ModelMessage, ModelResponse, TextPart, UserPromptPart
from pydantic_ai.models.function import AgentInfo, FunctionModel
from pydantic_ai.profiles import ModelProfile
from pydantic_ai_harness import ConvertFiles


def respond(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
    part = messages[0].parts[-1]
    assert isinstance(part, UserPromptPart) and not isinstance(part.content, str)
    image = part.content[1]
    assert isinstance(image, BinaryContent)
    return ModelResponse(parts=[TextPart(f'The model received {image.media_type}')])


# A model that reads only JPEG and PNG, so the BMP below is converted.
model = FunctionModel(respond, profile=ModelProfile(supported_image_media_types=frozenset({'image/jpeg', 'image/png'})))
agent = Agent(model, capabilities=[ConvertFiles()])

buffer = io.BytesIO()
Image.new('RGB', (8, 8), 'red').save(buffer, format='BMP')
photo = BinaryContent(buffer.getvalue(), media_type='image/bmp')

result = agent.run_sync(['What is in this image?', photo])
print(result.output)
#> The model received image/png

The history keeps the BMP; only the request to the model carries the PNG. A HEIC photo works the same way, and is sent as JPEG.

What gets converted

Before each model request, ConvertFiles looks at the ModelProfile of the model that serves that request. Every BinaryContent image in a user prompt or a tool result whose media type is not in the profile’s supported_image_media_types is converted:

  • HEIC, HEIF, and AVIF images become JPEG, since a PNG of a phone photo is several times larger. If the profile lists no JPEG, they become PNG.
  • Every other image, such as BMP, TIFF, or GIF, becomes PNG. If the profile lists no PNG, it becomes JPEG. A GIF keeps its first frame, and an image in a mode PNG can’t hold, such as a CMYK TIFF, becomes RGBA.
  • An image whose type the profile lists is sent as it is.
  • A profile that lists neither JPEG nor PNG leaves the image as it is.

The conversion applies to the request only. The message history keeps the original image, so a later request served by a model that reads the original type, for example after a fallback, gets the original. A converted tool-result image keeps its identifier.

A model whose profile has no supported_image_media_types reads any image, so nothing is converted for it. A model with supports_image_input=False is skipped too: it needs FileUnderstanding or the tool-result note, not a different image type. If an image fails to convert, for example corrupt bytes labelled image/heic, it is sent as it was and the run continues.

Only raster formats are decoded: HEIF, AVIF, BMP, TIFF, GIF, JPEG, PNG, and WebP. Pillow identifies a file by its content, not by the media type it is labelled with, so a file in any other format Pillow can open, such as EPS, is left as it is. An image with more than max_pixels pixels (width times height, 25_000_000 by default) is sent as it is, without being decoded, and so is one Pillow rejects as a decompression bomb.

What it does not do

  • Files given by URL are not converted: only bytes are, since converting a URL would mean downloading it.
  • Audio, video, and documents are not converted.
  • Images are not resized. Downscaling large images is planned with pydantic/pydantic-ai#12403.

Composition

With FileUnderstanding, ConvertFiles declares its ordering ahead of FileUnderstanding, so images are converted first regardless of which order you list them in capabilities=[...]:

from pydantic_ai import Agent
from pydantic_ai.capabilities import FileUnderstanding
from pydantic_ai_harness import ConvertFiles

agent = Agent(
    'anthropic:claude-sonnet-5-5',
    capabilities=[ConvertFiles(), FileUnderstanding(fallback_subagent_model='openai:gpt-6.1-sol')],
)

A converted image is one the model can read, so FileUnderstanding leaves it alone instead of replacing it with a text description, while still handling non-image files and images that fail to convert.

With ModelFallback, each candidate is judged on its own profile, so one that reads HEIC receives the original and one that doesn’t receives a conversion. A FallbackModel has no profile of its own, because which of its models answers is not known when the request is prepared, so ConvertFiles leaves its requests alone. Use ModelFallback to get per-candidate conversion.

Caching

History sends the original image on every turn, so converted images are kept in a bounded cache, keyed by a hash of the media type and bytes plus the target type. max_cached (default 128) bounds the entry count and max_cached_bytes (default 64 << 20, 64 MiB) bounds the total cached bytes; setting either to 0 keeps none. An image whose converted bytes exceed max_cached_bytes is skipped without evicting existing entries, and older entries are dropped least recently used first until both limits hold. The cache lives on the ConvertFiles instance, so one instance shared by several runs shares its cache. It is not used under a durable execution engine; see Durable execution.

Telemetry

Each conversion emits a convert_file span through ctx.tracer with these attributes:

  • convert_files.source_media_type and convert_files.target_media_type
  • convert_files.source_bytes and convert_files.target_bytes
  • convert_files.cache_hit: True when the converted image came from the cache

A failed conversion records the exception on the span and sends the original. The span holds no image content, including when trace_include_content is enabled. An image that needs no conversion emits no span.

Durable execution

Under a durable execution engine, each conversion runs as a durable operation named convert, under the capability’s id (convert_files by default). The conversions of one request are scheduled together. The engine records each result once and does not compute it again on replay, so a replay does not depend on the Pillow or codec build, and the work runs in an activity or step rather than in workflow code, so Temporal’s workflow task deadline does not apply to it. A recorded operation is part of the run’s history, so id must stay the same for a run to replay.

The image goes through the engine’s payloads as base64, into the operation and back out as the converted image. On Temporal, the payload size limit applies, so an image larger than about 1.5 MB, or one whose converted copy is, fails the operation. History sends the original each turn, so the operation runs again on every request that carries the image, and the instance cache described above is not used: whether an operation is scheduled depends only on the messages, so a replay on another worker makes the same calls.

Outside a durable engine, the conversion runs in a worker thread, so it does not block the event loop.

See the source.

API reference

ConvertFiles

Bases: AbstractCapability[AgentDepsT]

Convert images the model can’t read into a type it can, so the model reads the image itself.

Before each attempt at a request, every image in a user prompt or a tool result whose media type the ModelProfile of the model serving that attempt leaves out of supported_image_media_types is converted: to JPEG for a HEIC, HEIF or AVIF photo and to PNG for anything else, or to whichever of the two the model reads. The converted image goes out with that request only; the message history keeps the original, so a later model that reads the original type gets it.

A model whose profile lists no image media types reads any image, so nothing is converted for it, and one that doesn’t read images at all is left to FileUnderstanding or the tool-result note. An image that fails to convert, such as a corrupt file, one in a format outside the raster formats ConvertFiles decodes, or one larger than max_pixels, is sent as it was. A file given by URL is left as it is: only bytes are converted.

Under a durable execution engine the conversion is a durable operation named convert, recorded once per request and not recomputed on replay.

Attributes

max_cached

How many converted images to keep, most recently used first; 0 keeps none. History sends the original again each turn, so the same image would otherwise be converted on every request. Not used under a durable execution engine, where the recorded operation takes its place.

Type: int Default: 128

max_cached_bytes

Total bytes of converted images to keep in the cache (64 MiB by default); 0 keeps none. An image larger than this is not cached, and older entries are evicted until both max_cached and max_cached_bytes hold.

Type: int Default: 64 << 20

max_pixels

Images with more pixels than this (width times height) are sent as they are, without being decoded.

Type: int Default: 25000000

id

One per agent by default: two resolve to one through combine, which keeps the last.

Type: str | None Default: 'convert_files'

Methods

get_ordering
def get_ordering() -> CapabilityOrdering

Convert before FileUnderstanding judges the same profile, so a convertible image isn’t described instead.

Returns

CapabilityOrdering

prepare_model_request

@async

def prepare_model_request(
    ctx: RunContext[AgentDepsT],
    request_context: ModelRequestContext,
) -> ModelRequestContext

Convert the images the model serving this attempt can’t read, in the request’s copy of the messages.

Returns

ModelRequestContext