Skip to content

Commit 97b0b48

Browse files
authored
Close #208: more careful translating of images to/from Inspect (#211)
1 parent 9cf9159 commit 97b0b48

File tree

2 files changed

+9
-5
lines changed

2 files changed

+9
-5
lines changed

chatlas/_inspect.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
ContentToolResult,
1515
ContentUnion,
1616
)
17+
from ._content_pdf import parse_data_url
1718
from ._turn import Turn
1819

1920
if TYPE_CHECKING:
@@ -166,7 +167,9 @@ def chatlas_content_as_inspect(content: ContentUnion) -> InspectContent:
166167
elif isinstance(content, ContentImageRemote):
167168
return itool.ContentImage(image=content.url, detail=content.detail)
168169
elif isinstance(content, ContentImageInline):
169-
return itool.ContentImage(image=content.data or "", detail="auto")
170+
# Reconstruct the data URL from the base64 data and content type
171+
data_url = f"data:{content.image_content_type};base64,{content.data or ''}"
172+
return itool.ContentImage(image=data_url, detail="auto")
170173
elif isinstance(content, ContentPDF):
171174
return itool.ContentDocument(
172175
document=base64.b64encode(content.data).decode("ascii"),
@@ -199,11 +202,11 @@ def inspect_content_as_chatlas(content: str | InspectContent) -> Content:
199202
if content.image.startswith("http://") or content.image.startswith("https://"):
200203
return ContentImageRemote(url=content.image, detail=content.detail)
201204
else:
202-
# derive content_type from base64 data
205+
# Parse data URL to extract content type and base64 data
203206
# e.g., data:image/png;base64,....
204-
content_type = content.image.split(":")[1].split(";")[0]
207+
content_type, base64_data = parse_data_url(content.image)
205208
return ContentImageInline(
206-
data=content.image,
209+
data=base64_data,
207210
image_content_type=content_type, # type: ignore
208211
)
209212
if isinstance(content, itool.ContentDocument):

tests/test_inspect.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -510,7 +510,7 @@ def test_image_inline_translation(self):
510510
original = ContentImageInline(
511511
image_content_type="image/png",
512512
data=(
513-
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAA"
513+
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAA"
514514
"AAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="
515515
),
516516
)
@@ -519,6 +519,7 @@ def test_image_inline_translation(self):
519519

520520
assert isinstance(recovered, ContentImageInline)
521521
assert recovered.image_content_type == original.image_content_type
522+
assert recovered.data == original.data
522523

523524
def test_pdf_translation(self):
524525
original = ContentPDF(data=b"fake pdf content", filename="document.pdf")

0 commit comments

Comments
 (0)