Skip to content

Encode file event bytes as base64 in JSON - #373

Open
anbuzin wants to merge 1 commit into
mainfrom
encode-file-events
Open

anbuzin wants to merge 1 commit into
mainfrom
encode-file-events

Conversation

@anbuzin

@anbuzin anbuzin commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

Replaying a message with a binary file like a PNG could fail when you tried to dump its file event as JSON. We now encode bytes as base64, just like FilePart, even when the bytes are valid UTF-8. Strings like URLs and Python-mode dumps are unchanged.

import base64

# before: event.model_dump_json() raises PydanticSerializationError on non-UTF-8 file bytes
data = base64.b64encode(event.data).decode("ascii")
payload = event.model_copy(update={"data": data}).model_dump_json()

# after: model_dump_json() encodes the bytes as base64
payload = event.model_dump_json()

FileEvent accepts bytes, but its default JSON encoding treats them as
UTF-8. Binary data can raise a serialization error, and ASCII bytes
are written as raw text instead of the base64 used by FilePart.

Use Pydantic's standard base64 encoder for JSON only. Keep strings
unchanged and preserve bytes in Python-mode dumps.

Add tests for binary, ASCII and empty bytes, string data, JSON round
trips, and replayed file events.
@anbuzin anbuzin added the fix Bug fix label Nov 20, 2026
@vercel

vercel Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
ai-python Ready Ready Preview, v0 Nov 20, 2026 12:08am UTC

This branch was successfully deployed

1 active deployment
Preview — f0548683 Deployed Nov 20, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

fix Bug fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant