|
| 1 | +import base64 |
| 2 | +import mimetypes |
| 3 | +import os |
| 4 | +from typing import Any |
| 5 | + |
| 6 | +import pydantic |
| 7 | + |
| 8 | +from dspy.adapters.types.base_type import Type |
| 9 | + |
| 10 | + |
| 11 | +class File(Type): |
| 12 | + """A file input type for DSPy. |
| 13 | + See https://platform.openai.com/docs/api-reference/chat/create#chat_create-messages-user_message-content-array_of_content_parts-file_content_part-file for specification. |
| 14 | +
|
| 15 | + The file_data field should be a data URI with the format: |
| 16 | + data:<mime_type>;base64,<base64_encoded_data> |
| 17 | +
|
| 18 | + Example: |
| 19 | + ```python |
| 20 | + import dspy |
| 21 | +
|
| 22 | + class QA(dspy.Signature): |
| 23 | + file: dspy.File = dspy.InputField() |
| 24 | + summary = dspy.OutputField() |
| 25 | + program = dspy.Predict(QA) |
| 26 | + result = program(file=dspy.File.from_path("./research.pdf")) |
| 27 | + print(result.summary) |
| 28 | + ``` |
| 29 | + """ |
| 30 | + |
| 31 | + file_data: str | None = None |
| 32 | + file_id: str | None = None |
| 33 | + filename: str | None = None |
| 34 | + |
| 35 | + model_config = pydantic.ConfigDict( |
| 36 | + frozen=True, |
| 37 | + str_strip_whitespace=True, |
| 38 | + validate_assignment=True, |
| 39 | + extra="forbid", |
| 40 | + ) |
| 41 | + |
| 42 | + @pydantic.model_validator(mode="before") |
| 43 | + @classmethod |
| 44 | + def validate_input(cls, values: Any) -> Any: |
| 45 | + if isinstance(values, cls): |
| 46 | + return { |
| 47 | + "file_data": values.file_data, |
| 48 | + "file_id": values.file_id, |
| 49 | + "filename": values.filename, |
| 50 | + } |
| 51 | + |
| 52 | + if isinstance(values, dict): |
| 53 | + if "file_data" in values or "file_id" in values or "filename" in values: |
| 54 | + return values |
| 55 | + raise ValueError("Value of `dspy.File` must contain at least one of: file_data, file_id, or filename") |
| 56 | + |
| 57 | + return encode_file_to_dict(values) |
| 58 | + |
| 59 | + def format(self) -> list[dict[str, Any]]: |
| 60 | + try: |
| 61 | + file_dict = {} |
| 62 | + if self.file_data: |
| 63 | + file_dict["file_data"] = self.file_data |
| 64 | + if self.file_id: |
| 65 | + file_dict["file_id"] = self.file_id |
| 66 | + if self.filename: |
| 67 | + file_dict["filename"] = self.filename |
| 68 | + |
| 69 | + return [{"type": "file", "file": file_dict}] |
| 70 | + except Exception as e: |
| 71 | + raise ValueError(f"Failed to format file for DSPy: {e}") |
| 72 | + |
| 73 | + def __str__(self): |
| 74 | + return self.serialize_model() |
| 75 | + |
| 76 | + def __repr__(self): |
| 77 | + parts = [] |
| 78 | + if self.file_data is not None: |
| 79 | + if self.file_data.startswith("data:"): |
| 80 | + # file data has "data:text/plain;base64,..." format |
| 81 | + mime_type = self.file_data.split(";")[0].split(":")[1] |
| 82 | + len_data = len(self.file_data.split("base64,")[1]) if "base64," in self.file_data else len(self.file_data) |
| 83 | + parts.append(f"file_data=<DATA_URI({mime_type}, {len_data} chars)>") |
| 84 | + else: |
| 85 | + len_data = len(self.file_data) |
| 86 | + parts.append(f"file_data=<DATA({len_data} chars)>") |
| 87 | + if self.file_id is not None: |
| 88 | + parts.append(f"file_id='{self.file_id}'") |
| 89 | + if self.filename is not None: |
| 90 | + parts.append(f"filename='{self.filename}'") |
| 91 | + return f"File({', '.join(parts)})" |
| 92 | + |
| 93 | + @classmethod |
| 94 | + def from_path(cls, file_path: str, filename: str | None = None, mime_type: str | None = None) -> "File": |
| 95 | + """Create a File from a local file path. |
| 96 | +
|
| 97 | + Args: |
| 98 | + file_path: Path to the file to read |
| 99 | + filename: Optional filename to use (defaults to basename of path) |
| 100 | + mime_type: Optional MIME type (defaults to auto-detection from file extension) |
| 101 | + """ |
| 102 | + if not os.path.isfile(file_path): |
| 103 | + raise ValueError(f"File not found: {file_path}") |
| 104 | + |
| 105 | + with open(file_path, "rb") as f: |
| 106 | + file_bytes = f.read() |
| 107 | + |
| 108 | + if filename is None: |
| 109 | + filename = os.path.basename(file_path) |
| 110 | + |
| 111 | + if mime_type is None: |
| 112 | + mime_type, _ = mimetypes.guess_type(file_path) |
| 113 | + if mime_type is None: |
| 114 | + mime_type = "application/octet-stream" |
| 115 | + |
| 116 | + encoded_data = base64.b64encode(file_bytes).decode("utf-8") |
| 117 | + file_data = f"data:{mime_type};base64,{encoded_data}" |
| 118 | + |
| 119 | + return cls(file_data=file_data, filename=filename) |
| 120 | + |
| 121 | + @classmethod |
| 122 | + def from_bytes( |
| 123 | + cls, file_bytes: bytes, filename: str | None = None, mime_type: str = "application/octet-stream" |
| 124 | + ) -> "File": |
| 125 | + """Create a File from raw bytes. |
| 126 | +
|
| 127 | + Args: |
| 128 | + file_bytes: Raw bytes of the file |
| 129 | + filename: Optional filename |
| 130 | + mime_type: MIME type (defaults to 'application/octet-stream') |
| 131 | + """ |
| 132 | + encoded_data = base64.b64encode(file_bytes).decode("utf-8") |
| 133 | + file_data = f"data:{mime_type};base64,{encoded_data}" |
| 134 | + return cls(file_data=file_data, filename=filename) |
| 135 | + |
| 136 | + @classmethod |
| 137 | + def from_file_id(cls, file_id: str, filename: str | None = None) -> "File": |
| 138 | + """Create a File from an uploaded file ID.""" |
| 139 | + return cls(file_id=file_id, filename=filename) |
| 140 | + |
| 141 | + |
| 142 | +def encode_file_to_dict(file_input: Any) -> dict: |
| 143 | + """ |
| 144 | + Encode various file inputs to a dict with file_data, file_id, and/or filename. |
| 145 | +
|
| 146 | + Args: |
| 147 | + file_input: Can be a file path (str), bytes, or File instance. |
| 148 | +
|
| 149 | + Returns: |
| 150 | + dict: A dictionary with file_data, file_id, and/or filename keys. |
| 151 | + """ |
| 152 | + if isinstance(file_input, File): |
| 153 | + result = {} |
| 154 | + if file_input.file_data is not None: |
| 155 | + result["file_data"] = file_input.file_data |
| 156 | + if file_input.file_id is not None: |
| 157 | + result["file_id"] = file_input.file_id |
| 158 | + if file_input.filename is not None: |
| 159 | + result["filename"] = file_input.filename |
| 160 | + return result |
| 161 | + |
| 162 | + elif isinstance(file_input, str): |
| 163 | + if os.path.isfile(file_input): |
| 164 | + file_obj = File.from_path(file_input) |
| 165 | + else: |
| 166 | + raise ValueError(f"Unrecognized file string: {file_input}; must be a valid file path") |
| 167 | + |
| 168 | + return { |
| 169 | + "file_data": file_obj.file_data, |
| 170 | + "filename": file_obj.filename, |
| 171 | + } |
| 172 | + |
| 173 | + elif isinstance(file_input, bytes): |
| 174 | + file_obj = File.from_bytes(file_input) |
| 175 | + return {"file_data": file_obj.file_data} |
| 176 | + |
| 177 | + else: |
| 178 | + raise ValueError(f"Unsupported file input type: {type(file_input)}") |
0 commit comments