diff --git a/ollama/_types.py b/ollama/_types.py index 293bfa8..589c7aa 100644 --- a/ollama/_types.py +++ b/ollama/_types.py @@ -166,9 +166,14 @@ class Image(BaseModel): return b64encode(self.value.read_bytes() if isinstance(self.value, Path) else self.value).decode() if isinstance(self.value, str): - if Path(self.value).exists(): - return b64encode(Path(self.value).read_bytes()).decode() + try: + if Path(self.value).exists(): + return b64encode(Path(self.value).read_bytes()).decode() + except Exception: + # Long base64 string can't be wrapped in Path, so try to treat as base64 string + pass + # String might be a file path, but might not exist if self.value.split('.')[-1] in ('png', 'jpg', 'jpeg', 'webp'): raise ValueError(f'File {self.value} does not exist') diff --git a/tests/test_type_serialization.py b/tests/test_type_serialization.py index e3e8268..8200ce3 100644 --- a/tests/test_type_serialization.py +++ b/tests/test_type_serialization.py @@ -19,6 +19,12 @@ def test_image_serialization_base64_string(): assert img.model_dump() == b64_str # Should return as-is if valid base64 +def test_image_serialization_long_base64_string(): + b64_str = 'dGVzdCBiYXNlNjQgc3RyaW5n' * 1000 + img = Image(value=b64_str) + assert img.model_dump() == b64_str # Should return as-is if valid base64 + + def test_image_serialization_plain_string(): img = Image(value='not a path or base64') assert img.model_dump() == 'not a path or base64' # Should return as-is