DSPy: The framework for programming—not prompting—language models
Python
fix(adapters): prevent implicit resource loading during validation (#10111)
Isaac Millerc69136b29aca
diff --git a/docs/docs/api/primitives/Audio.md b/docs/docs/api/primitives/Audio.mdindex 129d9b358..d917cc1f6 100644--- a/docs/docs/api/primitives/Audio.md+++ b/docs/docs/api/primitives/Audio.md@@ -11,6 +11,7 @@- format- from_array- from_file+ - from_path- from_url- is_streamable- parse_lm_responsediff --git a/docs/docs/api/primitives/Image.md b/docs/docs/api/primitives/Image.mdindex fc46ce9cc..0d2eec91a 100644--- a/docs/docs/api/primitives/Image.md+++ b/docs/docs/api/primitives/Image.md@@ -11,6 +11,7 @@- format- from_PIL- from_file+ - from_path- from_url- is_streamable- parse_lm_responsediff --git a/docs/docs/diving-deeper/adapters.md b/docs/docs/diving-deeper/adapters.mdindex da08cb8b5..4d03c909c 100644--- a/docs/docs/diving-deeper/adapters.md+++ b/docs/docs/diving-deeper/adapters.md@@ -123,14 +123,17 @@ Types adapters know how to render and parse beyond Python’s standard ones. Eac**`dspy.adapters.types.Type`**The base class. Subclass it (it’s a `pydantic.BaseModel`) and implement `format()` to plug in a new type. Adapters wrap the output of `format()` with `<<CUSTOM-TYPE-START-IDENTIFIER>>...<<END-IDENTIFIER>>` so multi-modal content can be inserted into a single message stream and later split out.-**`dspy.Image(url, download=False, verify=True)`**-URL, local path, bytes, or PIL image. `format()` returns the provider’s image content block (`{"type": "image_url", "image_url": {"url": ...}}`). `download=True` fetches the image and base64-encodes it, useful when the LM provider can’t reach the URL.+**`dspy.Image(source)`**-**`dspy.Audio(data, audio_format)`**-Base64 audio data plus format string (`"wav"`, `"mp3"`). Renders as the provider’s audio content block.+URL reference, data URI, bytes, or PIL image. `format()` returns the provider’s image content block (`{"type": "image_url", "image_url": {"url": ...}}`). Ordinary construction and adapter parsing never access the filesystem or network. Use `Image.from_path(path)` to read a local file or `Image.from_url(url)` to download and base64-encode a remote resource. The deprecated direct call `Image(url, download=True)` also downloads for compatibility through 3.3; migrate it to `Image.from_url(url)`.-**`dspy.File(file_data=None, file_id=None, filename=None)`**-Either a data URI or a file ID (some providers preupload files and reference them by ID).+**`dspy.Audio(source)`**++A data URI, in-memory bytes, or array data; raw base64 must be passed as `Audio(data=..., audio_format=...)`. Renders as the provider’s audio content block. Use `Audio.from_path(path)` or `Audio.from_url(url)` for resource loading.++**`dspy.File(file_data=None, file_id=None, filename=None)`**++Either in-memory bytes, a data URI, or a file ID (some providers preupload files and reference them by ID). Use `File.from_path(path)` to read a local file.**`dspy.Code(code, language="python")`**Code with a class-level `language` parameter. `dspy.Code["java"]` produces a Code subclass typed for Java. `format()` returns the raw string — no wrapper, no fencing.@@ -150,6 +153,25 @@ The list of tool calls the LM produced, parsed from native function-calling resp**`dspy.adapters.types.Citations`**Declared as a default native response type. When the provider returns citations natively (e.g., Anthropic), adapters extract them through the type’s `parse_lm_response`.+### Migrating resource loading in 3.3++In DSPy 3.3, constructing or validating `Image`, `Audio`, and `File` values no longer interprets locator-shaped strings as instructions to read a local file or fetch a remote URL. This keeps LM output parsing and other validation paths from implicitly granting access to the host. Resource loading now requires an explicit factory:++| Before 3.3 | 3.3 replacement | Behavior |+| --- | --- | --- |+| `Image(path)` | `Image.from_path(path)` | Read and embed a local image |+| `Image(url, download=True)` | `Image.from_url(url)` | Download and embed a remote image |+| `Image.from_url(url)` or `Image.from_url(url, download=False)` | `Image(url)` | Keep a non-downloading URL reference |+| `Audio(path)` | `Audio.from_path(path)` | Read and embed a local audio file |+| `Audio(url)` | `Audio.from_url(url)` | Download and embed remote audio |+| `File(path)` | `File.from_path(path)` | Read and embed a local file |+| `Image.from_file(path)` | `Image.from_path(path)` | Replace the deprecated alias |+| `Audio.from_file(path)` | `Audio.from_path(path)` | Replace the deprecated alias |++Safe in-memory inputs such as data URIs, bytes, PIL images, audio arrays, and structured dictionaries remain supported. The deprecated direct call `Image(url, download=True)` continues to work with a warning through 3.3; `Image.from_file()`, `Image.from_PIL()`, and `Audio.from_file()` are also scheduled for removal in 3.4.++`Image.from_url()` and `Audio.from_url()` perform synchronous, caller-initiated HTTP requests and follow redirects. They do not validate destinations against an SSRF allowlist, so applications must validate or allowlist URLs derived from untrusted input before calling them.+### Configuring which adapter to use- **`dspy.configure(adapter=dspy.JSONAdapter())`** — process-wide default.diff --git a/docs/docs/learn/programming/signatures.md b/docs/docs/learn/programming/signatures.mdindex 403ca5ec8..9b3da5f97 100644--- a/docs/docs/learn/programming/signatures.md+++ b/docs/docs/learn/programming/signatures.md@@ -164,7 +164,7 @@ class DogPictureSignature(dspy.Signature):image_url = "https://picsum.photos/id/237/200/300"classify = dspy.Predict(DogPictureSignature)-classify(image_1=dspy.Image.from_url(image_url))+classify(image_1=dspy.Image(image_url))```**Possible Output:**diff --git a/docs/docs/tutorials/audio/index.ipynb b/docs/docs/tutorials/audio/index.ipynbindex 41969510f..1ecec9e38 100644--- a/docs/docs/tutorials/audio/index.ipynb+++ b/docs/docs/tutorials/audio/index.ipynb@@ -301,7 +301,7 @@" f.write(response.content)\n"," with open(wav_path, \"rb\") as f:\n"," encoded = base64.b64encode(f.read()).decode(\"utf-8\")\n",- " return dspy.Audio(data=encoded, format=\"wav\")"+ " return dspy.Audio(data=encoded, audio_format=\"wav\")"]},{diff --git a/docs/docs/tutorials/image_generation_prompting/index.ipynb b/docs/docs/tutorials/image_generation_prompting/index.ipynbindex cc266699e..8fd18a511 100644--- a/docs/docs/tutorials/image_generation_prompting/index.ipynb+++ b/docs/docs/tutorials/image_generation_prompting/index.ipynb@@ -101,7 +101,7 @@" result = fal_client.result(\"fal-ai/flux-pro/v1.1-ultra\", request_id)\n"," url = result[\"images\"][0][\"url\"]\n","\n",- " return dspy.Image.from_url(url)\n",+ " return dspy.Image(url)\n","\n","def display_image(image):\n"," url = image.url\n",diff --git a/dspy/adapters/types/audio.py b/dspy/adapters/types/audio.pyindex 0ceb734b7..5ecdbe421 100644--- a/dspy/adapters/types/audio.py+++ b/dspy/adapters/types/audio.py@@ -2,7 +2,9 @@ import base64import ioimport mimetypesimport os+import warningsfrom typing import Any, Union+from urllib.parse import urlparseimport pydanticimport requests@@ -23,6 +25,15 @@ def _normalize_audio_format(audio_format: str) -> str:class Audio(Type):+ """An audio input type for DSPy.++ Construct from in-memory values only: a data URI string, raw ``bytes`` (with+ ``audio_format=``), a numpy-like array, a ``{"data", "audio_format"}`` dict, or another+ ``Audio``. Raw base64 is passed as ``Audio(data=..., audio_format=...)``. Construction and+ adapter parsing never access the filesystem or network; use :meth:`from_path` to read a local+ file, :meth:`from_url` to download a remote resource, or :meth:`from_array` for array data.+ """+data: straudio_format: str@@ -31,19 +42,32 @@ class Audio(Type):extra="forbid",)+ def __init__(self, *args, **data):+ if len(args) > 1:+ raise TypeError(f"Audio expected at most 1 positional argument, received {len(args)}")+ if args:+ if "data" in data:+ raise TypeError("Audio received data as both a positional and keyword argument")+ value = args[0]+ sampling_rate = data.pop("sampling_rate", None)+ audio_format = data.pop("audio_format", None)+ if audio_format is not None and _carries_own_format(value):+ raise TypeError(+ "Audio received audio_format alongside an input that already carries its format; provide only one"+ )+ if sampling_rate is not None and not hasattr(value, "shape"):+ raise TypeError("Audio received sampling_rate for a non-array input; it only applies to array data")+ normalized = encode_audio(value, sampling_rate=sampling_rate or 16000, format=audio_format or "wav")+ normalized.update(data)+ data = normalized+ super().__init__(**data)+def format(self) -> list[dict[str, Any]]:try:data = self.dataexcept Exception as e:raise ValueError(f"Failed to format audio for DSPy: {e}")- return [{- "type": "input_audio",- "input_audio": {- "data": data,- "format": self.audio_format- }- }]-+ return [{"type": "input_audio", "input_audio": {"data": data, "format": self.audio_format}}]@pydantic.model_validator(mode="before")@classmethod@@ -56,11 +80,24 @@ class Audio(Type):return encode_audio(values)@classmethod- def from_url(cls, url: str) -> "Audio":+ def from_url(cls, url: str, verify: bool = True) -> "Audio":"""Download an audio file from URL and encode it as base64.++ Security: this performs an explicit, caller-initiated fetch and applies no+ SSRF protection beyond requiring an HTTP(S) scheme. Like ``requests.get``, it+ will reach private, loopback, or cloud-metadata hosts and follow redirects to+ them. When ``url`` is derived from untrusted input, the caller is responsible+ for validating the host against an allowlist before calling this method.++ Args:+ url: The URL of the audio to download.+ verify: Whether to verify SSL certificates. Set to False for self-signed certs."""- response = requests.get(url)+ parsed_url = urlparse(url)+ if parsed_url.scheme not in ("http", "https") or not parsed_url.netloc:+ raise ValueError(f"Audio.from_url requires an HTTP(S) URL, received: {url}")+ response = requests.get(url, verify=verify)response.raise_for_status()mime_type = response.headers.get("Content-Type", "audio/wav")if not mime_type.startswith("audio/"):@@ -73,7 +110,7 @@ class Audio(Type):return cls(data=encoded_data, audio_format=audio_format)@classmethod- def from_file(cls, file_path: str) -> "Audio":+ def from_path(cls, file_path: str) -> "Audio":"""Read local audio file and encode it as base64."""@@ -95,9 +132,17 @@ class Audio(Type):return cls(data=encoded_data, audio_format=audio_format)@classmethod- def from_array(- cls, array: Any, sampling_rate: int, format: str = "wav"- ) -> "Audio":+ def from_file(cls, file_path: str) -> "Audio":+ """Deprecated alias for :meth:`from_path`."""+ warnings.warn(+ "Audio.from_file is deprecated and will be removed in 3.4; use Audio.from_path instead.",+ DeprecationWarning,+ stacklevel=2,+ )+ return cls.from_path(file_path)++ @classmethod+ def from_array(cls, array: Any, sampling_rate: int, format: str = "wav") -> "Audio":"""Process numpy-like array and encode it as base64. Uses sampling rate and audio format for encoding."""@@ -122,33 +167,38 @@ class Audio(Type):length = len(self.data)return f"Audio(data=<AUDIO_BASE_64_ENCODED({length})>, audio_format='{self.audio_format}')"++def _carries_own_format(value: Any) -> bool:+ """Whether an audio input already carries its own format (making audio_format redundant)."""+ if isinstance(value, Audio):+ return True+ if isinstance(value, dict) and "audio_format" in value:+ return True+ return isinstance(value, str) and value.startswith("data:audio/")++def encode_audio(audio: Union[str, bytes, dict, "Audio", Any], sampling_rate: int = 16000, format: str = "wav") -> dict:"""Encode audio to a dict with 'data' and 'audio_format'.-- Accepts: local file path, URL, data URI, dict, Audio instance, numpy array, or bytes (with known format).++ Accepts in-memory data: data URI, dict, Audio instance, numpy array, or bytes."""if isinstance(audio, dict) and "data" in audio and "audio_format" in audio:return audioelif isinstance(audio, Audio):return {"data": audio.data, "audio_format": audio.audio_format}elif isinstance(audio, str) and audio.startswith("data:audio/"):- try:- header, b64data = audio.split(",", 1)- mime = header.split(";")[0].split(":")[1]- audio_format = mime.split("/")[1]-- audio_format = _normalize_audio_format(audio_format)-- return {"data": b64data, "audio_format": audio_format}- except Exception as e:- raise ValueError(f"Malformed audio data URI: {e}")- elif isinstance(audio, str) and os.path.isfile(audio):- a = Audio.from_file(audio)- return {"data": a.data, "audio_format": a.audio_format}- elif isinstance(audio, str) and audio.startswith("http"):- a = Audio.from_url(audio)- return {"data": a.data, "audio_format": a.audio_format}+ header, separator, b64data = audio.partition(",")+ mime = header.removeprefix("data:").split(";", 1)[0]+ _, format_separator, audio_format = mime.partition("/")+ if not separator or not format_separator or not audio_format:+ raise ValueError("Malformed audio data URI")+ return {"data": b64data, "audio_format": _normalize_audio_format(audio_format)}+ elif isinstance(audio, str):+ raise ValueError(+ "String audio inputs must be data URIs. "+ "Load local files with Audio.from_path() and remote resources with Audio.from_url()."+ )elif SF_AVAILABLE and hasattr(audio, "shape"):a = Audio.from_array(audio, sampling_rate=sampling_rate, format=format)return {"data": a.data, "audio_format": a.audio_format}diff --git a/dspy/adapters/types/file.py b/dspy/adapters/types/file.pyindex cbb0cc3d7..e2723abb2 100644--- a/dspy/adapters/types/file.py+++ b/dspy/adapters/types/file.py@@ -15,6 +15,11 @@ class File(Type):The file_data field should be a data URI with the format:data:<mime_type>;base64,<base64_encoded_data>+ Construct from in-memory values only: raw ``bytes``, a data URI string, a+ ``{"file_data"|"file_id"|"filename"}`` dict, or another ``File``. Construction and adapter+ parsing never access the filesystem; use :meth:`from_path` to read a local file,+ :meth:`from_bytes` for raw bytes, or :meth:`from_file_id` to reference a preuploaded file.+Examples:```pythonimport dspy@@ -39,6 +44,20 @@ class File(Type):extra="forbid",)+ def __init__(self, *args, **data):+ if len(args) > 1:+ raise TypeError(f"File expected at most 1 positional argument, received {len(args)}")+ if args:+ normalized = encode_file_to_dict(args[0])+ overlap = sorted(set(normalized) & set(data))+ if overlap:+ raise TypeError(+ f"File received {', '.join(overlap)} from both the positional source and keyword arguments"+ )+ normalized.update(data)+ data = normalized+ super().__init__(**data)+@pydantic.model_validator(mode="before")@classmethoddef validate_input(cls, values: Any) -> Any:@@ -79,7 +98,9 @@ class File(Type):if self.file_data.startswith("data:"):# file data has "data:text/plain;base64,..." formatmime_type = self.file_data.split(";")[0].split(":")[1]- len_data = len(self.file_data.split("base64,")[1]) if "base64," in self.file_data else len(self.file_data)+ len_data = (+ len(self.file_data.split("base64,")[1]) if "base64," in self.file_data else len(self.file_data)+ )parts.append(f"file_data=<DATA_URI({mime_type}, {len_data} chars)>")else:len_data = len(self.file_data)@@ -144,7 +165,7 @@ def encode_file_to_dict(file_input: Any) -> dict:Encode various file inputs to a dict with file_data, file_id, and/or filename.Args:- file_input: Can be a file path (str), bytes, or File instance.+ file_input: Can be bytes, a data URI string, a structured dictionary, or a File instance.Returns:dict: A dictionary with file_data, file_id, and/or filename keys.@@ -159,16 +180,18 @@ def encode_file_to_dict(file_input: Any) -> dict:result["filename"] = file_input.filenamereturn result+ elif isinstance(file_input, dict):+ if "file_data" in file_input or "file_id" in file_input or "filename" in file_input:+ return file_input+ raise ValueError("Value of `dspy.File` must contain at least one of: file_data, file_id, or filename")+elif isinstance(file_input, str):- if os.path.isfile(file_input):- file_obj = File.from_path(file_input)- else:- raise ValueError(f"Unrecognized file string: {file_input}; must be a valid file path")-- return {- "file_data": file_obj.file_data,- "filename": file_obj.filename,- }+ if file_input.startswith("data:"):+ return {"file_data": file_input}+ raise ValueError(+ f"String file inputs must be data URIs, received: {file_input}. "+ "Load local files with File.from_path()."+ )elif isinstance(file_input, bytes):file_obj = File.from_bytes(file_input)diff --git a/dspy/adapters/types/image.py b/dspy/adapters/types/image.pyindex fc24768b8..273621f58 100644--- a/dspy/adapters/types/image.py+++ b/dspy/adapters/types/image.py@@ -14,12 +14,16 @@ from dspy.adapters.types.base_type import Typetry:from PIL import Image as PILImage+ from PIL import UnidentifiedImageErrorPIL_AVAILABLE = Trueexcept ImportError:PIL_AVAILABLE = False+_UNSET = object()++class Image(Type):url: str@@ -30,42 +34,72 @@ class Image(Type):extra="forbid",)- def __init__(self, url: Any = None, *, download: bool = False, verify: bool = True, **data):+ def __init__(self, source: Any = None, /, *, download: Any = _UNSET, verify: Any = _UNSET, **data):"""Create an Image.Parameters----------- url:- The image source. Supported values include+ source:+ The positional-only image source. Supported values include- - ``str``: HTTP(S)/GS URL or local file path+ - ``str``: HTTP(S)/GS URL or an encoded data URI- ``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.-- verify:- Whether to verify SSL certificates when downloading images from URLs.- Set to False for self-signed certificates. Default is True.+ download, verify:+ Deprecated. Use :meth:`from_url` (which accepts ``verify``) to download a+ remote image, or :meth:`from_path` for a local file. Accepted for one release+ with a warning: ``download=True`` eagerly fetches an HTTP(S) ``source``.Any additional keyword arguments are passed to :class:`pydantic.BaseModel`.++ Ordinary construction never touches the filesystem or network. Local files and remote+ resources must be loaded explicitly with :meth:`from_path` and :meth:`from_url`. The+ deprecated positional ``Image(url, download=True)`` compatibility call also downloads."""- 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"}:+ download_requested = download is not _UNSET+ verify_requested = verify is not _UNSET+ if (download_requested or verify_requested) and source is None:+ # `download`/`verify` are a compatibility shim for the positional constructor+ # `Image(url, download=True)`. They must never be honored through the validation+ # path: pydantic routes dict data into `__init__`, so an untrusted value such as+ # `{"url": "http://169.254.169.254/...", "download": true}` would otherwise trigger+ # a server-side fetch during output parsing. Requiring a positional source keeps the+ # shim reachable only from direct developer construction.+ raise TypeError(+ "`download` and `verify` are only valid with a positional image source; "+ "use Image.from_url(url, verify=...) to download a remote image."+ )+ if download_requested or verify_requested:+ warnings.warn(+ "The `download` and `verify` arguments to Image() are deprecated and will be removed in "+ "3.4. Use Image.from_url(url, verify=...) to download a remote image, or "+ "Image.from_path(path) for a local file.",+ DeprecationWarning,+ stacklevel=2,+ )++ if source is not None and "url" in data:+ raise TypeError("Image received both `source` and `url`; provide only one image source")++ if source is not None:+ # Support a positional source while retaining the Pydantic ``url`` field.+ if isinstance(source, dict) and set(source.keys()) == {"url"}:# Legacy dict form from previous model validator.- data["url"] = url["url"]+ data["url"] = source["url"]else:- # ``url`` may be a string, bytes, or a PIL image.- data["url"] = url+ data["url"] = source- if "url" in data:+ url = data.get("url")+ if download_requested and download and isinstance(url, str) and _is_http_url(url):+ # Legacy download=True path: eagerly fetch the remote URL.+ data["url"] = _encode_image_from_url(url, verify=verify if verify_requested else True)+ elif "url" in data:# Normalize any accepted input into a base64 data URI or plain URL.- data["url"] = encode_image(data["url"], download_images=download, verify=verify)+ data["url"] = encode_image(data["url"])# Delegate the rest of initialization to pydantic's BaseModel.super().__init__(**data)@@ -79,27 +113,40 @@ class Image(Type):return [{"type": "image_url", "image_url": {"url": image_url}}]@classmethod- def from_url(cls, url: str, download: bool = False):- warnings.warn(- "Image.from_url is deprecated; use Image(url) instead.",- DeprecationWarning,- stacklevel=2,- )- return cls(url, download=download)+ def from_url(cls, url: str, verify: bool = True) -> "Image":+ """Download an HTTP(S) resource and encode it as a data URI.++ Security: this performs an explicit, caller-initiated fetch and applies no+ SSRF protection beyond requiring an HTTP(S) scheme. Like ``requests.get``, it+ will reach private, loopback, or cloud-metadata hosts and follow redirects to+ them. When ``url`` is derived from untrusted input, the caller is responsible+ for validating the host against an allowlist before calling this method.+ """+ if not _is_http_url(url):+ raise ValueError(f"Image.from_url requires an HTTP(S) URL, received: {url}")+ return cls(_encode_image_from_url(url, verify=verify))++ @classmethod+ def from_path(cls, file_path: str) -> "Image":+ """Read a local file and encode it as a data URI."""+ if not os.path.isfile(file_path):+ raise ValueError(f"File not found: {file_path}")+ return cls(_encode_image_from_file(file_path))@classmethod- def from_file(cls, file_path: str):+ def from_file(cls, file_path: str) -> "Image":+ """Deprecated alias for :meth:`from_path`."""warnings.warn(- "Image.from_file is deprecated; use Image(file_path) instead.",+ "Image.from_file is deprecated and will be removed in 3.4; use Image.from_path instead.",DeprecationWarning,stacklevel=2,)- return cls(file_path)+ return cls.from_path(file_path)@classmethoddef from_PIL(cls, pil_image): # noqa: N802warnings.warn(- "Image.from_PIL is deprecated; use Image(pil_image) instead.",+ "Image.from_PIL is deprecated and will be removed in 3.4; use Image(pil_image) instead.",DeprecationWarning,stacklevel=2,)@@ -125,41 +172,38 @@ def is_url(string: str) -> bool:return False-def encode_image(image: Union[str, bytes, "PILImage.Image", dict], download_images: bool = False, verify: bool = True) -> str:+def _is_http_url(string: str) -> bool:+ """Check if a string is an HTTP(S) URL."""+ try:+ result = urlparse(string)+ return result.scheme in ("http", "https") and bool(result.netloc)+ except ValueError:+ return False+++def encode_image(image: Union[str, bytes, "PILImage.Image", dict]) -> str:"""- Encode an image or file to a base64 data URI.+ Normalize an in-memory image or preserve a remote image reference.Args:- image: The image or file to encode. Can be a PIL Image, file path, URL, or data URI.- download_images: Whether to download images from URLs.- verify: Whether to verify SSL certificates when downloading images.+ image: A PIL Image, bytes, URL reference, data URI, or Image.Returns:- str: The data URI of the file or the URL if download_images is False.+ str: A data URI or remote URL reference.Raises:ValueError: If the file type is not supported."""if isinstance(image, dict) and "url" in image:- # NOTE: Not doing other validation for now- return image["url"]+ return encode_image(image["url"])elif isinstance(image, str):if image.startswith("data:"):# Already a data URIreturn image- elif os.path.isfile(image):- # File path- return _encode_image_from_file(image)elif is_url(image):- # URL- if download_images:- return _encode_image_from_url(image, verify=verify)- else:- # Return the URL as is- return image+ return imageelse:- # Unsupported string format- raise ValueError(f"Unrecognized file string: {image}; If this file type should be supported, please open an issue.")+ raise ValueError(f"Unrecognized image string: {image}. Local files must be loaded with Image.from_path().")elif PIL_AVAILABLE and isinstance(image, PILImage.Image):# PIL Imagereturn _encode_pil_image(image)@@ -167,12 +211,14 @@ def encode_image(image: Union[str, bytes, "PILImage.Image", dict], download_imag# Raw bytesif not PIL_AVAILABLE:raise ImportError("Pillow is required to process image bytes.")- img = PILImage.open(io.BytesIO(image))+ try:+ img = PILImage.open(io.BytesIO(image))+ except UnidentifiedImageError as e:+ raise ValueError(f"Bytes could not be identified as an image: {e}") from ereturn _encode_pil_image(img)elif isinstance(image, Image):return image.urlelse:- print(f"Unsupported image type: {type(image)}")raise ValueError(f"Unsupported image type: {type(image)}")@@ -192,7 +238,7 @@ def _encode_image_from_file(file_path: str) -> str:def _encode_image_from_url(image_url: str, verify: bool = True) -> str:"""Encode a file from a URL to a base64 data URI.-+Args:image_url: The URL of the image to download.verify: Whether to verify SSL certificates. Set to False for self-signed certs.@@ -243,8 +289,6 @@ def is_image(obj) -> bool:if isinstance(obj, str):if obj.startswith("data:"):return True- elif os.path.isfile(obj):- return Trueelif is_url(obj):return Truereturn Falsediff --git a/tests/adapters/test_resource_loading.py b/tests/adapters/test_resource_loading.pynew file mode 100644index 000000000..7725e7abb--- /dev/null+++ b/tests/adapters/test_resource_loading.py@@ -0,0 +1,202 @@+import base64++import pytest+from pydantic import TypeAdapter, ValidationError++import dspy+++def _forbid_host_io(monkeypatch):+ """Make any filesystem read or outbound request fail the test."""++ def fail_open(*args, **kwargs):+ pytest.fail("resource handling attempted a filesystem read")++ def fail_request(*args, **kwargs):+ pytest.fail("resource handling attempted a network request")++ monkeypatch.setattr("builtins.open", fail_open)+ monkeypatch.setattr("dspy.adapters.types.image.requests.get", fail_request)+ monkeypatch.setattr("dspy.adapters.types.audio.requests.get", fail_request)+++# Locator-shaped inputs an attacker could supply. Neither construction nor the validation/parse+# path may trigger host I/O, whether the call raises (paths, non-data-URI strings) or is retained+# as a reference (Image URLs).+_LOCATOR_INPUTS = [+ (dspy.Image, {"url": "/etc/passwd"}),+ (dspy.Image, "/etc/passwd"),+ (dspy.Image, {"url": "https://evil.example/secret.png"}),+ (dspy.Audio, "/etc/passwd"),+ (dspy.Audio, "https://evil.example/secret.wav"),+ (dspy.File, "/etc/passwd"),+ (dspy.File, "https://evil.example/secret.bin"),+]++[email protected](("annotation", "value"), _LOCATOR_INPUTS)+def test_construction_performs_no_host_io(monkeypatch, annotation, value):+ # The constructor is reachable from untrusted application input (e.g. dspy.Image(user_string));+ # it must never dereference a locator.+ _forbid_host_io(monkeypatch)+ try:+ annotation(value)+ except (ValueError, TypeError):+ pass++[email protected](("annotation", "value"), _LOCATOR_INPUTS)+def test_validation_performs_no_host_io(monkeypatch, annotation, value):+ # validate_python is the path adapters use to coerce untrusted LM output (and pydantic uses for+ # nested models / deserialization); it must never dereference a locator either.+ _forbid_host_io(monkeypatch)+ try:+ TypeAdapter(annotation).validate_python(value)+ except (ValueError, TypeError, ValidationError):+ pass+++def test_image_url_constructor_does_not_download(monkeypatch):+ def fail_request(*args, **kwargs):+ pytest.fail("Image construction attempted to download a remote resource")++ monkeypatch.setattr("dspy.adapters.types.image.requests.get", fail_request)++ image = dspy.Image("https://example.com/image.png")++ assert image.url == "https://example.com/image.png"+++def test_image_validation_rejects_download_without_host_io(monkeypatch):+ _forbid_host_io(monkeypatch)++ with pytest.raises((TypeError, ValidationError), match="only valid with a positional image source"):+ TypeAdapter(dspy.Image).validate_python({"url": "http://169.254.169.254/latest/meta-data", "download": True})+++def test_image_validation_rejects_download_with_source_keyword_without_host_io(monkeypatch):+ _forbid_host_io(monkeypatch)++ with pytest.raises((TypeError, ValidationError), match="only valid with a positional image source"):+ TypeAdapter(dspy.Image).validate_python({"source": "http://169.254.169.254/latest/meta-data", "download": True})+++def test_image_positional_download_compatibility_shim(monkeypatch):+ class Response:+ content = b"remote bytes"+ headers = {"Content-Type": "image/png"}++ def raise_for_status(self):+ return None++ monkeypatch.setattr("dspy.adapters.types.image.requests.get", lambda *args, **kwargs: Response())++ with pytest.warns(DeprecationWarning, match="download.*deprecated"):+ image = dspy.Image("https://example.com/image.png", download=True)++ assert base64.b64decode(image.url.split(",", 1)[1]) == b"remote bytes"+++def test_explicit_local_resource_factories(tmp_path):+ image_path = tmp_path / "image.png"+ image_path.write_bytes(b"image bytes")+ audio_path = tmp_path / "audio.wav"+ audio_path.write_bytes(b"audio bytes")+ file_path = tmp_path / "document.txt"+ file_path.write_bytes(b"file bytes")++ assert base64.b64decode(dspy.Image.from_path(str(image_path)).url.split(",", 1)[1]) == b"image bytes"+ assert base64.b64decode(dspy.Audio.from_path(str(audio_path)).data) == b"audio bytes"+ assert base64.b64decode(dspy.File.from_path(str(file_path)).file_data.split(",", 1)[1]) == b"file bytes"+++def test_audio_from_file_is_deprecated_alias(tmp_path):+ audio_path = tmp_path / "audio.wav"+ audio_path.write_bytes(b"audio bytes")++ with pytest.warns(DeprecationWarning, match="Audio.from_file is deprecated"):+ aliased = dspy.Audio.from_file(str(audio_path))++ assert base64.b64decode(aliased.data) == b"audio bytes"+++ ("factory", "mime_type"), [(dspy.Image.from_url, "image/png"), (dspy.Audio.from_url, "audio/wav")]+)+def test_explicit_remote_resource_factories(monkeypatch, factory, mime_type):+ class Response:+ def __init__(self):+ self.content = b"remote bytes"+ self.headers = {"Content-Type": mime_type}++ def raise_for_status(self):+ return None++ module = "image" if factory == dspy.Image.from_url else "audio"+ monkeypatch.setattr(f"dspy.adapters.types.{module}.requests.get", lambda *args, **kwargs: Response())++ resource = factory(f"https://example.com/resource.{mime_type.split('/', 1)[1]}")+ encoded = resource.url.split(",", 1)[1] if isinstance(resource, dspy.Image) else resource.data+ assert base64.b64decode(encoded) == b"remote bytes"+++def test_in_memory_resource_construction():+ image = dspy.Image(+ base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=")+ )+ audio = dspy.Audio(b"audio bytes", audio_format="wav")+ file = dspy.File(b"file bytes")++ assert image.url.startswith("data:image/")+ assert base64.b64decode(audio.data) == b"audio bytes"+ assert file.file_data.startswith("data:application/octet-stream;base64,")+++ ("source", "match"),+ [("clip.wav", r"Audio\.from_path"), ("https://example.com/a.wav", r"Audio\.from_url")],+)+def test_audio_positional_string_must_be_data_uri_even_with_format(source, match):+ with pytest.raises(ValueError, match=match):+ dspy.Audio(source, audio_format="wav")+++ "source",+ [+ "data:audio/wav;base64,AA==",+ {"data": "AA==", "audio_format": "wav"},+ dspy.Audio(data="AA==", audio_format="wav"),+ ],+)+def test_audio_rejects_audio_format_for_inputs_that_carry_one(source):+ with pytest.raises(TypeError, match="already carries its format"):+ dspy.Audio(source, audio_format="mp3")++[email protected]("source", [b"audio bytes", "data:audio/wav;base64,AA=="])+def test_audio_rejects_sampling_rate_for_non_array_inputs(source):+ with pytest.raises(TypeError, match="sampling_rate"):+ dspy.Audio(source, sampling_rate=44100)+++def test_audio_from_url_passes_verify(monkeypatch):+ captured = {}++ class Response:+ def __init__(self):+ self.content = b"remote bytes"+ self.headers = {"Content-Type": "audio/wav"}++ def raise_for_status(self):+ return None++ def fake_get(url, **kwargs):+ captured.update(kwargs)+ return Response()++ monkeypatch.setattr("dspy.adapters.types.audio.requests.get", fake_get)++ dspy.Audio.from_url("https://example.com/a.wav", verify=False)++ assert captured["verify"] is Falsediff --git a/tests/signatures/test_adapter_file.py b/tests/signatures/test_adapter_file.pyindex e44ab900e..2a900424b 100644--- a/tests/signatures/test_adapter_file.py+++ b/tests/signatures/test_adapter_file.py@@ -152,11 +152,9 @@ def test_file_str():assert "<<CUSTOM-TYPE-END-IDENTIFIER>>" in str_repr-def test_encode_file_to_dict_from_path(sample_text_file):- result = encode_file_to_dict(sample_text_file)- assert "file_data" in result- assert result["file_data"].startswith("data:text/plain;base64,")- assert "filename" in result+def test_encode_file_to_dict_rejects_path(sample_text_file):+ with pytest.raises(ValueError, match=r"File\.from_path"):+ encode_file_to_dict(sample_text_file)def test_encode_file_to_dict_from_bytes():@@ -165,8 +163,25 @@ def test_encode_file_to_dict_from_bytes():assert result["file_data"].startswith("data:application/octet-stream;base64,")+def test_file_constructor_from_bytes():+ file_obj = dspy.File(b"test content", filename="test.txt")+ assert file_obj.file_data.startswith("data:application/octet-stream;base64,")+ assert file_obj.filename == "test.txt"+++def test_file_constructor_from_data_uri():+ data_uri = "data:text/plain;base64,aGVsbG8="+ file_obj = dspy.File(data_uri)+ assert file_obj.file_data == data_uri+++def test_file_constructor_rejects_conflicting_keyword():+ with pytest.raises(TypeError, match="file_data"):+ dspy.File(b"test content", file_data="data:text/plain;base64,aGVsbG8=")++def test_invalid_file_string():- with pytest.raises(ValueError, match="Unrecognized"):+ with pytest.raises(ValueError, match=r"File\.from_path"):encode_file_to_dict("https://this_is_not_a_file_path")diff --git a/tests/signatures/test_adapter_image.py b/tests/signatures/test_adapter_image.pyindex c0fe94371..f50e100fd 100644--- a/tests/signatures/test_adapter_image.py+++ b/tests/signatures/test_adapter_image.py@@ -1,5 +1,7 @@+import base64import osimport tempfile+import warningsfrom io import BytesIOimport pydantic@@ -24,7 +26,7 @@ def sample_pil_image():@pytest.fixturedef sample_dspy_image_download():url = "https://images.dog.ceo/breeds/dane-great/n02109047_8912.jpg"- return dspy.Image(url, download=True)+ return dspy.Image.from_url(url)@pytest.fixture@@ -343,8 +345,8 @@ def test_pdf_url_support():"""Test support for PDF files from URLs"""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(pdf_url, download=True)+ # Download the PDF into a dspy.Image data URI.+ pdf_image = dspy.Image.from_url(pdf_url)# The data URI should contain application/pdf in the MIME typeassert "data:application/pdf" in pdf_image.url@@ -381,7 +383,7 @@ def test_different_mime_types():for file_type, url in file_urls.items():# Download and encode- encoded = encode_image(url, download_images=True)+ encoded = dspy.Image.from_url(url).url# Check for correct MIME type in the encoded data - using 'in' instead of startswith# to account for possible parameters in the MIME type@@ -402,7 +404,7 @@ def test_mime_type_from_response_headers():assert "pdf" in expected_mime_type.lower()# Encode with download to test MIME type from headers- encoded = encode_image(pdf_url, download_images=True)+ encoded = dspy.Image.from_url(pdf_url).url# The encoded data should contain the correct MIME typeassert "application/pdf" in encoded@@ -422,7 +424,7 @@ def test_pdf_from_file():try:# Create a dspy.Image from the file- pdf_image = dspy.Image(tmp_file_path)+ pdf_image = dspy.Image.from_path(tmp_file_path)# The constructor encodes the file into a data URI we can inspect directlyassert "data:application/pdf" in pdf_image.url@@ -463,41 +465,104 @@ def test_image_repr():assert "base64" in str(pil_image)-def test_from_methods_warn(tmp_path):- """Deprecated from_* methods emit warnings"""+def test_image_constructor_supports_positional_source_and_url_keyword():+ source = "https://example.com/dog.jpg"++ assert dspy.Image(source).url == source+ assert dspy.Image(url=source).url == source++ with pytest.raises(pydantic.ValidationError, match="source"):+ dspy.Image(source=source)++ with pytest.raises(TypeError, match="both `source` and `url`"):+ dspy.Image(source, url=source)+++def test_canonical_factories_do_not_warn(tmp_path):tmp_file = tmp_path / "test.png"tmp_file.write_bytes(b"pngdata")- with pytest.warns(DeprecationWarning):+ with pytest.MonkeyPatch.context() as monkeypatch:+ response = type("Response", (), {"content": b"pngdata", "headers": {"Content-Type": "image/png"}})()+ response.raise_for_status = lambda: None+ monkeypatch.setattr("dspy.adapters.types.image.requests.get", lambda *args, **kwargs: response)dspy.Image.from_url("https://example.com/dog.jpg")- with pytest.warns(DeprecationWarning):++ with warnings.catch_warnings():+ warnings.simplefilter("error", DeprecationWarning)+ dspy.Image.from_path(str(tmp_file))+++def test_deprecated_factory_aliases_warn(tmp_path):+ tmp_file = tmp_path / "test.png"+ tmp_file.write_bytes(b"pngdata")++ with pytest.warns(DeprecationWarning, match="Image.from_file is deprecated"):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"""+ """A string that is neither a data URI nor a URL raises."""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)+ with pytest.raises(ValueError, match="Unrecognized"):+ dspy.Image(invalid_string)+-def test_pil_image_with_download_parameter():- """Test behavior when PIL image is passed with download=True"""+def test_positional_local_path_hard_breaks(tmp_path, monkeypatch):+ """Image(path) raises pointing at from_path, and never touches the filesystem to decide."""+ tmp_file = tmp_path / "photo.png"+ tmp_file.write_bytes(b"pngdata")++ monkeypatch.setattr("builtins.open", lambda *a, **k: pytest.fail("Image(path) read the filesystem"))++ with pytest.raises(ValueError, match=r"Image\.from_path"):+ dspy.Image(str(tmp_file))+++def test_deprecated_download_true_downloads(monkeypatch):+ response = type("Response", (), {"content": b"pngdata", "headers": {"Content-Type": "image/png"}})()+ response.raise_for_status = lambda: None+ monkeypatch.setattr("dspy.adapters.types.image.requests.get", lambda *args, **kwargs: response)++ with pytest.warns(DeprecationWarning, match="`download` and `verify`"):+ image = dspy.Image("https://example.com/dog.jpg", download=True)++ assert image.url.startswith("data:image/png;base64,")+ assert base64.b64decode(image.url.split(",", 1)[1]) == b"pngdata"+++def test_deprecated_download_false_keeps_reference():+ source = "https://example.com/dog.jpg"+ with pytest.warns(DeprecationWarning, match="`download` and `verify`"):+ image = dspy.Image(source, download=False)+ assert image.url == source+++def test_deprecated_verify_warns_without_download():+ source = "https://example.com/dog.jpg"+ with pytest.warns(DeprecationWarning, match="`download` and `verify`"):+ image = dspy.Image(source, verify=False)+ assert image.url == source+++def test_pil_image_with_deprecated_download_still_encodes():sample_pil = PILImage.new("RGB", (60, 30), color="red")+ with pytest.warns(DeprecationWarning, match="`download` and `verify`"):+ image = dspy.Image(sample_pil, download=True)+ assert image.url.startswith("data:image/")+- # 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)+def test_from_path_missing_file():+ with pytest.raises(ValueError, match="File not found"):+ dspy.Image.from_path("/nonexistent/image.png")- # 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.url+def test_unidentifiable_bytes_raise_value_error():+ with pytest.raises(ValueError, match="could not be identified as an image"):+ dspy.Image(b"not an image")diff --git a/tests/teleprompt/test_gepa.py b/tests/teleprompt/test_gepa.pyindex 4d88a78ea..64c3a274f 100644--- a/tests/teleprompt/test_gepa.py+++ b/tests/teleprompt/test_gepa.py@@ -188,7 +188,6 @@ def test_workflow_with_custom_instruction_proposer_and_component_selector():Example(clock_photo=dspy.Image("https://upload.wikimedia.org/wikipedia/commons/thumb/c/cf/Pendulum_clock_by_Jacob_Kock%2C_antique_furniture_photography%2C_IMG_0931_edit.jpg/500px-Pendulum_clock_by_Jacob_Kock%2C_antique_furniture_photography%2C_IMG_0931_edit.jpg",- download=False,),hour=8,minute=18,@@ -196,7 +195,6 @@ def test_workflow_with_custom_instruction_proposer_and_component_selector():Example(clock_photo=dspy.Image("https://upload.wikimedia.org/wikipedia/commons/thumb/a/a5/Telechron_clock_2H07-Br_Administrator.JPG/960px-Telechron_clock_2H07-Br_Administrator.JPG",- download=False,),hour=4,minute=16,