Fix tokenization of <|constrain|> content type in rendering#47
Merged
dkundel-openai merged 1 commit intoopenai:mainfrom Aug 9, 2025
Merged
Conversation
dkundel-openai
approved these changes
Aug 9, 2025
dkundel-openai
added a commit
that referenced
this pull request
Aug 9, 2025
)" This reverts commit 8a4645f.
This was referenced Aug 21, 2025
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
The recommended way to render a constrained JSON clause in Harmony is
.with_content_type("<|constrain|>json"). Unfortunately, the current code treats it as user input and doesn't tokenize into special tokens.Thus, the previous tool calls get rendered wrong into the token space by
encoding.render_conversation:This confuses the model and leads to invalid syntax for subsequent tool calling, especially on 20B model. See #27 (comment) for more context
If one renders text and encodes it back with special tokens allowed, the output is fixed. However, it opens an opportunity for prompt injection attacks as user input may now contain special tokens.
Instead, this PR handles the
<|constrain|>special case explicitly. Alternative would be to add explicit API like.with_content_type("json", contrain=True)but it feels like a bigger change.Minimal repro
Script
output before this PR
output after this PR