Skip to content

feat(decode): Add opt-in lossy mode and decode_bytes#123

Merged
gjtorikian merged 1 commit into
mainfrom
fix/decode-lossy-utf8
Jul 18, 2026
Merged

feat(decode): Add opt-in lossy mode and decode_bytes#123
gjtorikian merged 1 commit into
mainfrom
fix/decode-lossy-utf8

Conversation

@gjtorikian

Copy link
Copy Markdown
Collaborator

Summary

  • BPE tokens are byte-level, so a single character (an emoji, non-Latin scripts) can span multiple tokens. A common "trim text to N tokens" pattern can leave a prefix that isn't valid UTF-8, and decode raised Tiktoken::UnicodeError on it.
  • Adds an opt-in errors: :replace to decode, which substitutes invalid byte sequences with the Unicode replacement character (U+FFFD, ). The default stays :strict to preserve existing behavior.
  • Adds decode_bytes(tokens), which returns the raw decoded bytes as an ASCII-8BIT string with no UTF-8 validation (for callers who want to handle invalid sequences themselves)

Closes #122

BPE tokens are byte-level, so a single character can span several
tokens. The common "trim text to N tokens" pattern can leave a
prefix that is not valid UTF-8, and decode raised
Tiktoken::UnicodeError on it — diverging from Python tiktoken,
whose decode defaults to errors="replace".

Add an opt-in errors: :replace that substitutes invalid sequences
with U+FFFD, plus decode_bytes for the raw bytes. The default
stays :strict to preserve existing behavior. Also define
Tiktoken::UnicodeError eagerly at load, since it previously only
existed after the first decode error was raised.

Closes #122
@gjtorikian
gjtorikian merged commit 58d0ab6 into main Jul 18, 2026
10 of 12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

decode raises Tiktoken::UnicodeError when tokens are truncated mid multi-byte character (diverges from Python tiktoken)

1 participant