Skip to content

fix: apply surrogate-pair fixup in encode_with_unstable#575

Open
steps-re wants to merge 1 commit into
openai:mainfrom
steps-re:fix/encode-with-unstable-surrogate-pairs
Open

fix: apply surrogate-pair fixup in encode_with_unstable#575
steps-re wants to merge 1 commit into
openai:mainfrom
steps-re:fix/encode-with-unstable-surrogate-pairs

Conversation

@steps-re

@steps-re steps-re commented Jul 8, 2026

Copy link
Copy Markdown

Fixes #541.

encode and encode_ordinary both catch UnicodeEncodeError and re-encode the text through UTF-16 surrogatepass before retrying, so they handle strings containing surrogate pairs (e.g. "👍") correctly. encode_with_unstable was missing the same try/except, causing it to raise UnicodeEncodeError on identical input.

Change: wrap the inner _core_bpe.encode_with_unstable call in the same try/except that encode uses.

Test: test_encode_with_unstable_surrogate_pairs in tests/test_encoding.py verifies that:

  • A surrogate-pair string produces the same output as the equivalent codepoint ("👍").
  • A lone surrogate is treated as the replacement character, consistent with encode.

encode_with_unstable raised UnicodeEncodeError when given text containing
surrogate pairs (e.g. "👍"), while encode and encode_ordinary
handled the same input correctly by catching UnicodeEncodeError and
re-encoding through UTF-16 surrogatepass.

Apply the same try/except fixup to encode_with_unstable so all three
methods behave consistently for surrogate-pair inputs.

Fixes openai#541

Signed-off-by: Mike German <mike@stepsventures.com>
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.

encode_with_unstable does not handle surrogate pairs like encode

1 participant