diff --git a/src/strands/types/models/openai.py b/src/strands/types/models/openai.py index 96f758d5..0df1dda5 100644 --- a/src/strands/types/models/openai.py +++ b/src/strands/types/models/openai.py @@ -57,7 +57,17 @@ def format_request_message_content(cls, content: ContentBlock) -> dict[str, Any] if "image" in content: mime_type = mimetypes.types_map.get(f".{content['image']['format']}", "application/octet-stream") - image_data = content["image"]["source"]["bytes"].decode("utf-8") + image_bytes = content["image"]["source"]["bytes"] + try: + base64.b64decode(image_bytes, validate=True) + logger.warning( + "issue=<%s> | base64 encoded images will not be accepted in a future version", + "https://github.com/strands-agents/sdk-python/issues/252" + ) + except ValueError: + image_bytes = base64.b64encode(image_bytes) + + image_data = image_bytes.decode("utf-8") return { "image_url": { "detail": "auto", diff --git a/tests/strands/types/models/test_openai.py b/tests/strands/types/models/test_openai.py index 9db08bc9..2827969d 100644 --- a/tests/strands/types/models/test_openai.py +++ b/tests/strands/types/models/test_openai.py @@ -1,3 +1,4 @@ +import base64 import unittest.mock import pytest @@ -90,7 +91,24 @@ def system_prompt(): "image_url": { "detail": "auto", "format": "image/jpeg", - "url": "data:image/jpeg;base64,image", + "url": "data:image/jpeg;base64,aW1hZ2U=", + }, + "type": "image_url", + }, + ), + # Image - base64 encoded + ( + { + "image": { + "format": "jpg", + "source": {"bytes": base64.b64encode(b"image")}, + }, + }, + { + "image_url": { + "detail": "auto", + "format": "image/jpeg", + "url": "data:image/jpeg;base64,aW1hZ2U=", }, "type": "image_url", },