Skip to content

Converting images to data

Marvin can use OpenAI's vision API to process images and convert them into structured data, transforming unstructured information into native types that are appropriate for a variety of programmatic use cases.

The marvin.beta.cast function is an enhanced version of marvin.cast that accepts images as well as text.


Please note that vision support in Marvin is still in beta, as OpenAI has not finalized the vision API yet. While it works as expected, it is subject to change.

What it does

The cast function can cast images to structured types.

How it works

This involves a two-step process: first, a caption is generated for the image that is aligned with the structuring goal. Next, the actual cast operation is performed with an LLM.

Example: locations

We will cast this image to a Location type:

import marvin
from pydantic import BaseModel, Field

class Location(BaseModel):
    city: str
    state: str = Field(description="2-letter state abbreviation")

img = marvin.beta.Image(
result = marvin.beta.cast(img, target=Location)


assert result == Location(city="New York", state="NY")

Example: getting information about a book

We will cast this image to a Book to extract key information:

import marvin
from pydantic import BaseModel

class Book(BaseModel):
    title: str
    subtitle: str
    authors: list[str]

img = marvin.beta.Image(
result = marvin.beta.cast(img, target=Book)


assert result == Book(
    title='The Elements of Statistical Learning',
    subtitle='Data Mining, Inference, and Prediction',
    authors=['Trevor Hastie', 'Robert Tibshirani', 'Jerome Friedman']


If the target type isn't self-documenting, or you want to provide additional guidance, you can provide natural language instructions when calling cast in order to steer the output.

Example: checking groceries

Let's use this image to see if we got everything on our shopping list:

import marvin

shopping_list = ["bagels", "cabbage", "eggs", "apples", "oranges"]

missing_items = marvin.beta.cast(
    instructions=f"Did I forget anything on my list: {shopping_list}?",


assert missing_items == ["eggs", "oranges"]

Model parameters

You can pass parameters to the underlying API via the model_kwargs and vision_model_kwargs arguments of cast. These parameters are passed directly to the respective APIs, so you can use any supported parameter.

Async support

If you are using marvin in an async environment, you can use cast_async:

result = await marvin.beta.cast_async("one", int) 

assert result == 1