Break chat-template special tokens in content on open-model routes, and restore them in model output, with `ModelProfile.may_tokenize_special_tokens_in_content`
- Part of #12396
Many hosts of open-weight models encode chat-template tokens found in message content, such as <|im_start|>, as the real control token. Text from a tool, a file or a user can then close the current turn and open one in any role. A note can't fix that, because it sits in a turn the forged one has already closed.
On routes that can reach such a host, this PR puts a zero-width joiner (U+200D) inside each token before sending, and removes it again from what the model writes.
[!WARNING]
Compatibility impact: On open-model routes, text containing a chat-template special token now goes out with a zero-width joiner inside the token, and a zero-width character inside such a token in a model's text or tool call arguments is removed. An application that relies on sending these tokens as control tokens in user or tool text, or a test that snapshots those bytes, sees a change. Conversations whose history contains such a token move their cached prefix once, on the first request after upgrading.
Why this can ship in a minor release: It's a security-relevant fix to how content reaches the model. Text without such a token is byte-identical, and the new behavior is opt-out per model.
Migration: Pass profile={'may_tokenize_special_tokens_in_content': False} to the model, for text you trust or a host you've pinned that treats these tokens as text.
What changes
ModelProfile.may_tokenize_special_tokens_in_content, defaultFalse. Providers set it through one table,profiles/_special_tokens.py, so narrowing a route is one line. Tokenization is a property of the host, not the family: the same weights are text on one host and control tokens on the next, and a routing service can pick either, so a profile can't tell which it will get.- Routes with the flag: self-hosted servers, hosts of open-weight models, and, for every model that isn't only available from its own lab, routing services,
OpenAICompatibleProvider, LiteLLM andOpenAIProviderwith a non-OpenAI name. Other routes, including each lab's own API for its own models where it treats the tokens as text, keep it off. The table is the list. - The break, in
Model.prepare_messages, on the outgoing copy: user prompts, tool results, retry feedback, summaries sent as user text, and replayed text, tool names, tool call arguments and reasoning. A token split across adjacent text items is covered, including around aCachePoint, since some hosts join them before tokenizing. A token escaped in JSON arguments is covered too, since adapters decode them. Text files are broken where the adapter inlines them, so downloaded ones are covered too. - The restore, at the
Modelboundary:Model.__init_subclass__wraps each class'srequest,request_streamandbatch_decode. So every adapter, including third-party ones, is covered, and tools, output validation, users and stored history all see one value whichever way the response was produced. In a stream, only a zero-width character is ever held back, until what follows shows whether it's inside a token, so text without one is not delayed. Tool call arguments are read string by string as the JSON decoder reads them, escapes included, so the streamed deltas, the final response and the tool all get the same value, and only the joiner's own characters are dropped. There an escape still arriving is held back too.
The restore removes any zero-width character inside a token rather than only U+200D, because gpt-oss and Qwen sometimes write U+200C or U+200B when copying it. It applies to text and tool call arguments only. Ids and provider data are never touched, and signed reasoning stays as it is when the model accepts its signature, decided by Model.accepts_stateless_artifacts as the adapters decide it. Otherwise it's rendered as text without the signature, so it's broken like other text.
How this fits with #11813
#11813 removes escaping of user and tool text, because rewriting content cost fidelity, and it adds notes instead. This PR is a deliberate, narrow exception to its "no content rewriting" rule: on these routes, a note measurably doesn't hold, and the literal has to be broken. The two don't conflict in behavior: it's off by default, it's one character, and #11813's matcher already ignores zero-width characters, so a note can still fire on a broken token. The "byte for byte" sentence in its docs will need this exception added, whichever PR lands second. They touch nearby lines in models/__init__.py, which is a small merge conflict.
Measurements
Pydantic AI on pinned routes that tokenize, each family with its own tokens, n=8 per arm unless noted. A count check compared prompt token counts for the same text literal and broken. It found tokenization in the Qwen, DeepSeek, GLM, gpt-oss, Llama, MiniMax and older Kimi families on many hosts, and only text for closed models. Broken tokens were never tokenized. On the hosts checked per channel, user text, tool results, assistant history, tool call arguments, tool descriptions and system messages all tokenize.
Forged turn in a tool result, followed the operator's instructions instead:
| Family | Without the break | With the break |
|---|---|---|
| Qwen 3.8 27B | 0/16 | 15/24 |
| GLM 5.3 | 0/8 | 13/16 |
| DeepSeek V4.1 Flash | 5/8 | 16/16 |
| DeepSeek V4 Pro | 1/8 | 1/16 |
| Qwen3 Next | 0/8 | 0/16 |
| Llama 3.3 | 0/8 | 0/16 |
| gpt-oss-120b | 1/8 | 0/16 |
The last four follow the shape of a turn even as plain text, so this PR doesn't fix them: it removes the real turn boundary, not the model's habit.
Read a chat template and write it back (exact copy, ignoring a dropped final newline, which happens without this change too; runs that errored out are left out):
| Family | Off, tokenizing route | On, break only (no restore) | On, this PR |
|---|---|---|---|
| Qwen 3.8 27B | 0/8 | 1/8 | 8/8 |
| GLM 5.3 | 0/1 (7 never finished) | 0/8 | 7/8 |
| DeepSeek V4 Pro | 0/7 | 0/8 | 7/8 |
| gpt-oss-120b | 0/0 (8 never finished) | 0/8 | 8/8 |
On routes that treat the tokens as text, it stays level: Qwen 3.8 27B 8/8 off and 8/8 on, Kimi K3 8/8 and 8/8, gpt-oss-120b 8/8 and 8/8. A zero-width character reached a written file in 30 of 32 runs without the restore, and in 1 of 56 with it: a GLM run that lost the tokens outright and left bare joiners behind, which aren't inside a token, so nothing removed them. Without the break on these hosts the task fails because the model never sees the tokens as text.
Streamed, the same copy plus printing the file in the reply (a short file, n=4): Qwen 3.8 27B and DeepSeek V4.1 Flash were exact 4/4, with no zero-width character in the file or the stream. gpt-oss-120b wrote nothing on this file, which holds only tokens, and said it was empty, so that one isn't evidence either way.
Edit tool that matches exact text: 2 of 35 calls failed to find the text, none with a joiner in the search text. With the break and no restore, 6 of 11 Qwen calls failed, all 6 for that reason.
These are small samples from one prompt per family, for direction, and the wider re-measure happens after merge. They predate the later review fixes on this branch, which add token shapes and channels but don't change how the measured tokens are broken or restored. Gemma 4's one-sided tokens come from its prompt format docs and weren't measured.
Remaining costs and limitations
- A file that deliberately holds a broken token gets repaired if the model copies it, because it can't be told apart from a token we broke.
- Tool call arguments and response text can differ from the model's raw output in this one way. Replay sends the broken form, whichever form the model wrote, deterministically.
- MCP tool descriptions aren't covered. Tool definitions tokenize on these hosts too and an MCP server's descriptions are untrusted. Tool definitions, system prompts and instructions are left alone in this PR as the application's own channel. Tool descriptions from MCP servers need a follow-up.
- Models that follow the shape as plain text (see the table above) need something else, such as the lookalike notes this issue also asks for.
- A provider-fetched file URL can't be broken, as we never see its text.
- Tool call ids aren't broken, as the provider and the framework match on them.
Not in this PR
The rest of #12396 is the lookalike note for these tokens, which needs #11813 and #12364's detector, and replacing the -----END FILE fence with a <file> frame, which overlaps #11813's removal of inlined-file escaping. Both follow once #11813 is settled, so this says "Part of".
Checklist
- No breaking changes in accordance with the version policy.
- Any permitted compatibility impact has a label, warning, migration and release note, and an exact API-check waiver if the gate reports it.
- PR title is fit for the release changelog.
š¤ Generated with Claude Code