DSPy: The framework for programming—not prompting—language models
Python
Deprecate Image from_* helpers in favor of flexible constructor (#8771)
Isaac Miller4d0b7e62b1d4
diff --git a/dspy/adapters/types/image.py b/dspy/adapters/types/image.pyindex 56e14801c..3ec2efd8a 100644--- a/dspy/adapters/types/image.py+++ b/dspy/adapters/types/image.py@@ -2,6 +2,7 @@ import base64import ioimport mimetypesimport os+import warningsfrom typing import Any, Unionfrom urllib.parse import urlparse@@ -28,6 +29,42 @@ class Image(Type):extra="forbid",)+ def __init__(self, url: Any = None, *, download: bool = False, **data):+ """Create an Image.++ Parameters+ ----------+ url:+ The image source. Supported values include++ - ``str``: HTTP(S)/GS URL or local file path+ - ``bytes``: raw image bytes+ - ``PIL.Image.Image``: a PIL image instance+ - ``dict`` with a single ``{"url": value}`` entry (legacy form)+ - already encoded data URI++ download:+ Whether remote URLs should be downloaded to infer their MIME type.++ Any additional keyword arguments are passed to :class:`pydantic.BaseModel`.+ """++ if url is not None and "url" not in data:+ # Support a positional argument while allowing ``url=`` in **data.+ if isinstance(url, dict) and set(url.keys()) == {"url"}:+ # Legacy dict form from previous model validator.+ data["url"] = url["url"]+ else:+ # ``url`` may be a string, bytes, or a PIL image.+ data["url"] = url++ if "url" in data:+ # Normalize any accepted input into a base64 data URI or plain URL.+ data["url"] = encode_image(data["url"], download_images=download)++ # Delegate the rest of initialization to pydantic's BaseModel.+ super().__init__(**data)+def format(self) -> list[dict[str, Any]] | str:try:image_url = encode_image(self.url)@@ -35,33 +72,32 @@ class Image(Type):raise ValueError(f"Failed to format image for DSPy: {e}")return [{"type": "image_url", "image_url": {"url": image_url}}]- @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'.")-- # If all my inits just call encode_image, should that be in this class@classmethoddef from_url(cls, url: str, download: bool = False):- return cls(url=encode_image(url, download))+ warnings.warn(+ "Image.from_url is deprecated; use Image(url) instead.",+ DeprecationWarning,+ stacklevel=2,+ )+ return cls(url, download=download)@classmethoddef from_file(cls, file_path: str):- return cls(url=encode_image(file_path))+ warnings.warn(+ "Image.from_file is deprecated; use Image(file_path) instead.",+ DeprecationWarning,+ stacklevel=2,+ )+ return cls(file_path)@classmethoddef from_PIL(cls, pil_image): # noqa: N802- return cls(url=encode_image(pil_image))+ warnings.warn(+ "Image.from_PIL is deprecated; use Image(pil_image) instead.",+ DeprecationWarning,+ stacklevel=2,+ )+ return cls(pil_image)def __str__(self):return self.serialize_model()@@ -116,8 +152,7 @@ def encode_image(image: Union[str, bytes, "PILImage.Image", dict], download_imagreturn imageelse:# Unsupported string format- print(f"Unsupported file string: {image}")- raise ValueError(f"Unsupported file string: {image}")+ raise ValueError(f"Unrecognized file string: {image}; If this file type should be supported, please open an issue.")elif PIL_AVAILABLE and isinstance(image, PILImage.Image):# PIL Imagereturn _encode_pil_image(image)diff --git a/tests/signatures/test_adapter_image.py b/tests/signatures/test_adapter_image.pyindex f458a489e..8537858ae 100644--- a/tests/signatures/test_adapter_image.py+++ b/tests/signatures/test_adapter_image.py@@ -23,7 +23,8 @@ def sample_pil_image():@pytest.fixturedef sample_dspy_image_download():- return dspy.Image.from_url("https://images.dog.ceo/breeds/dane-great/n02109047_8912.jpg", download=True)+ url = "https://images.dog.ceo/breeds/dane-great/n02109047_8912.jpg"+ return dspy.Image(url, download=True)@pytest.fixture@@ -33,7 +34,7 @@ def sample_url():@pytest.fixturedef sample_dspy_image_no_download():- return dspy.Image.from_url("https://images.dog.ceo/breeds/dane-great/n02109047_8912.jpg", download=False)+ return dspy.Image("https://images.dog.ceo/breeds/dane-great/n02109047_8912.jpg")def count_messages_with_image_url_pattern(messages):@@ -113,7 +114,7 @@ def test_basic_image_operations(test_case):# Convert string URLs to dspy.Image objectsinputs = {- k: dspy.Image.from_url(v) if isinstance(v, str) and k in ["image", "ui_image"] else v+ k: dspy.Image(v) if isinstance(v, str) and k in ["image", "ui_image"] else vfor k, v in test_case["inputs"].items()}@@ -152,7 +153,7 @@ def test_image_input_formats(actual_input = input_map[image_input]# TODO(isaacbmiller): Support the cases without direct dspy.Image coercionif image_input in ["pil_image", "encoded_pil_image"]:- pytest.xfail(f"{description} not fully supported without dspy.from_PIL")+ pytest.xfail(f"{description} not fully supported without dspy.Image coercion")result = predictor(image=actual_input, class_labels=["dog", "cat", "bird"])assert result.probabilities == expected["probabilities"]@@ -163,7 +164,7 @@ def test_predictor_save_load(sample_url, sample_pil_image):"""Test saving and loading predictors with image fields"""signature = "image: dspy.Image -> caption: str"examples = [- dspy.Example(image=dspy.Image.from_url(sample_url), caption="Example 1"),+ dspy.Example(image=dspy.Image(sample_url), caption="Example 1"),dspy.Example(image=sample_pil_image, caption="Example 2"),]@@ -176,7 +177,7 @@ def test_predictor_save_load(sample_url, sample_pil_image):loaded_predictor = dspy.Predict(signature)loaded_predictor.load(temp_file.name)- loaded_predictor(image=dspy.Image.from_url("https://example.com/dog.jpg"))+ loaded_predictor(image=dspy.Image("https://example.com/dog.jpg"))assert count_messages_with_image_url_pattern(lm.history[-1]["messages"]) == 2assert "<DSPY_IMAGE_START>" not in str(lm.history[-1]["messages"])@@ -186,8 +187,8 @@ def test_save_load_complex_default_types():examples = [dspy.Example(image_list=[- dspy.Image.from_url("https://example.com/dog.jpg"),- dspy.Image.from_url("https://example.com/cat.jpg"),+ dspy.Image("https://example.com/dog.jpg"),+ dspy.Image("https://example.com/cat.jpg"),],caption="Example 1",).with_inputs("image_list"),@@ -253,9 +254,9 @@ def test_save_load_complex_types(test_case):processed_input = {}for key, value in test_case["inputs"].items():if isinstance(value, str) and "http" in value:- processed_input[key] = dspy.Image.from_url(value)+ processed_input[key] = dspy.Image(value)elif isinstance(value, list) and value and isinstance(value[0], str):- processed_input[key] = [dspy.Image.from_url(url) for url in value]+ processed_input[key] = [dspy.Image(url) for url in value]else:processed_input[key] = value@@ -298,8 +299,8 @@ def test_save_load_pydantic_model():# Create model instancemodel_input = ImageModel(- image=dspy.Image.from_url("https://example.com/dog.jpg"),- image_list=[dspy.Image.from_url("https://example.com/cat.jpg")],+ image=dspy.Image("https://example.com/dog.jpg"),+ image_list=[dspy.Image("https://example.com/cat.jpg")],output="Multiple photos",)@@ -343,7 +344,7 @@ def test_pdf_url_support():pdf_url = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"# Create a dspy.Image object from the PDF URL with download=True- pdf_image = dspy.Image.from_url(pdf_url, download=True)+ pdf_image = dspy.Image(pdf_url, download=True)# The data URI should contain application/pdf in the MIME typeassert "data:application/pdf" in pdf_image.url@@ -421,9 +422,9 @@ def test_pdf_from_file():try:# Create a dspy.Image from the file- pdf_image = dspy.Image.from_file(tmp_file_path)+ pdf_image = dspy.Image(tmp_file_path)- # Check that the MIME type is correct+ # The constructor encodes the file into a data URI we can inspect directlyassert "data:application/pdf" in pdf_image.urlassert ";base64," in pdf_image.url@@ -447,7 +448,7 @@ def test_pdf_from_file():def test_image_repr():"""Test string representation of Image objects"""- url_image = dspy.Image.from_url("https://example.com/dog.jpg", download=False)+ url_image = dspy.Image("https://example.com/dog.jpg")assert str(url_image) == ("<<CUSTOM-TYPE-START-IDENTIFIER>>""[{'type': 'image_url', 'image_url': {'url': 'https://example.com/dog.jpg'}}]"@@ -456,7 +457,47 @@ def test_image_repr():assert repr(url_image) == "Image(url='https://example.com/dog.jpg')"sample_pil = PILImage.new("RGB", (60, 30), color="red")- pil_image = dspy.Image.from_PIL(sample_pil)+ pil_image = dspy.Image(sample_pil)assert str(pil_image).startswith("<<CUSTOM-TYPE-START-IDENTIFIER>>[{'type': 'image_url',")assert str(pil_image).endswith("<<CUSTOM-TYPE-END-IDENTIFIER>>")assert "base64" in str(pil_image)+++def test_from_methods_warn(tmp_path):+ """Deprecated from_* methods emit warnings"""+ tmp_file = tmp_path / "test.png"+ tmp_file.write_bytes(b"pngdata")++ with pytest.warns(DeprecationWarning):+ dspy.Image.from_url("https://example.com/dog.jpg")+ with pytest.warns(DeprecationWarning):+ dspy.Image.from_file(str(tmp_file))+ sample_pil = PILImage.new("RGB", (10, 10), color="blue")+ with pytest.warns(DeprecationWarning):+ dspy.Image.from_PIL(sample_pil)+++def test_invalid_string_format():+ """Test that invalid string formats raise a ValueError"""+ invalid_string = "this_is_not_a_url_or_file"++ # Should raise a ValueError and not pass the string through+ with pytest.raises(ValueError, match="Unrecognized") as warning_info:+ image = dspy.Image(invalid_string)++def test_pil_image_with_download_parameter():+ """Test behavior when PIL image is passed with download=True"""+ sample_pil = PILImage.new("RGB", (60, 30), color="red")++ # PIL image should be encoded regardless of download parameter+ image_no_download = dspy.Image(sample_pil)+ image_with_download = dspy.Image(sample_pil, download=True)++ # Both should result in base64 encoded data URIs+ assert image_no_download.url.startswith("data:")+ assert image_with_download.url.startswith("data:")+ assert "base64," in image_no_download.url+ assert "base64," in image_with_download.url++ # They should be identical since PIL images are always encoded+ assert image_no_download.url == image_with_download.urldiff --git a/tests/teleprompt/test_gepa_instruction_proposer.py b/tests/teleprompt/test_gepa_instruction_proposer.pyindex 358e6d90f..1efeb5c5a 100644--- a/tests/teleprompt/test_gepa_instruction_proposer.py+++ b/tests/teleprompt/test_gepa_instruction_proposer.py@@ -74,7 +74,7 @@ def test_reflection_lm_gets_structured_images():Verify reflection LM receives structured image messages, not serialized text."""student = dspy.Predict("image: dspy.Image -> label: str")- image = dspy.Image.from_url("https://example.com/test.jpg", download=False)+ image = dspy.Image("https://example.com/test.jpg")example = dspy.Example(image=image, label="dog").with_inputs("image")reflection_lm = DummyLM(@@ -243,7 +243,7 @@ def test_image_serialization_into_strings():student = dspy.Predict("image -> label")- image = dspy.Image.from_url("https://picsum.photos/id/237/200/300", download=False)+ image = dspy.Image("https://picsum.photos/id/237/200/300")examples = [dspy.Example(image=image, label="cat").with_inputs("image"),@@ -300,7 +300,7 @@ def test_image_serialization_into_strings():def test_default_proposer():student = dspy.Predict("image -> label")- image = dspy.Image.from_url("https://picsum.photos/id/237/200/300", download=False)+ image = dspy.Image("https://picsum.photos/id/237/200/300")examples = [dspy.Example(image=image, label="cat").with_inputs("image"),