Skip to content

dspy.Image

dspy.Image

Bases: BaseType

Functions

format() -> Union[list[dict[str, Any]], str]

Source code in dspy/adapters/types/image.py
def format(self) -> Union[list[dict[str, Any]], str]:
    try:
        image_url = encode_image(self.url)
    except Exception as e:
        raise ValueError(f"Failed to format image for DSPy: {e}")
    return [{"type": "image_url", "image_url": {"url": image_url}}]

from_PIL(pil_image) classmethod

Source code in dspy/adapters/types/image.py
@classmethod
def from_PIL(cls, pil_image):  # noqa: N802
    return cls(url=encode_image(pil_image))

from_file(file_path: str) classmethod

Source code in dspy/adapters/types/image.py
@classmethod
def from_file(cls, file_path: str):
    return cls(url=encode_image(file_path))

from_url(url: str, download: bool = False) classmethod

Source code in dspy/adapters/types/image.py
@classmethod
def from_url(cls, url: str, download: bool = False):
    return cls(url=encode_image(url, download))

serialize_model()

Source code in dspy/adapters/types/base_type.py
@pydantic.model_serializer()
def serialize_model(self):
    return f"{CUSTOM_TYPE_START_IDENTIFIER}{self.format()}{CUSTOM_TYPE_END_IDENTIFIER}"

validate_input(values) classmethod

Source code in dspy/adapters/types/image.py
@pydantic.model_validator(mode="before")
@classmethod
def validate_input(cls, values):
    # Allow the model to accept either a URL string or a dictionary with a single 'url' key
    if isinstance(values, str):
        # if a string, assume it's the URL directly and wrap it in a dict
        return {"url": values}
    elif isinstance(values, dict) and set(values.keys()) == {"url"}:
        # if it's a dict, ensure it has only the 'url' key
        return values
    elif isinstance(values, cls):
        return values.model_dump()
    else:
        raise TypeError("Expected a string URL or a dictionary with a key 'url'.")