From 21778c4909f3e4d173b194ae22c59fa964d0dca2 Mon Sep 17 00:00:00 2001 From: WitBlue6 <107780822+WitBlue6@users.noreply.github.com> Date: Thu, 1 Oct 2026 00:20:20 +0800 Subject: [PATCH] feat: accept base64 image data URIs --- ollama/_types.py | 10 ++++++++++ tests/test_image_data_uri.py | 25 +++++++++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 tests/test_image_data_uri.py diff --git a/ollama/_types.py b/ollama/_types.py index cf7264b5..83fddb0c 100644 --- a/ollama/_types.py +++ b/ollama/_types.py @@ -167,6 +167,16 @@ def serialize_model(self): return b64encode(self.value.read_bytes() if isinstance(self.value, Path) else self.value).decode() if isinstance(self.value, str): + if self.value.lower().startswith('data:'): + header, separator, encoded = self.value.partition(',') + if not separator or not encoded or not header.lower().startswith('data:image/') or not header.lower().endswith(';base64'): + raise ValueError('Invalid image data URI, expected a base64-encoded image') + try: + b64decode(encoded, validate=True) + except Exception as exc: + raise ValueError('Invalid image data URI, expected a base64-encoded image') from exc + return encoded + try: if Path(self.value).exists(): return b64encode(Path(self.value).read_bytes()).decode() diff --git a/tests/test_image_data_uri.py b/tests/test_image_data_uri.py new file mode 100644 index 00000000..7f6f782b --- /dev/null +++ b/tests/test_image_data_uri.py @@ -0,0 +1,25 @@ +import base64 + +import pytest + +from ollama._types import Image + + +def test_image_data_uri_serializes_as_base64(): + encoded = base64.b64encode(b'example image bytes').decode() + assert Image(value=f'data:image/png;base64,{encoded}').model_dump() == encoded + assert Image(value=f'DATA:IMAGE/PNG;BASE64,{encoded}').model_dump() == encoded + + +@pytest.mark.parametrize( + 'value', + [ + 'data:image/png,not-base64', + 'data:image/png;base64,invalid!', + 'data:image/png;base64,', + 'data:text/plain;base64,ZXhhbXBsZQ==', + ], +) +def test_invalid_image_data_uri_raises(value: str): + with pytest.raises(ValueError, match='Invalid image data URI'): + Image(value=value).model_dump()