Skip to content

fix(templating): default tojson ensure_ascii=False to prevent token bloat - #459

Open
Komeiji-Shiki wants to merge 1 commit into
theroyallab:mainfrom
Komeiji-Shiki:fix/template-tojson-ensure-ascii
Open

fix(templating): default tojson ensure_ascii=False to prevent token bloat#459
Komeiji-Shiki wants to merge 1 commit into
theroyallab:mainfrom
Komeiji-Shiki:fix/template-tojson-ensure-ascii

Conversation

@Komeiji-Shiki

Copy link
Copy Markdown

Problem

The chat template tojson filter (_tojson_compat in common/templating.py)
defaulted to ensure_ascii=True. When a Qwen3.5-style template renders tool
definitions via {{- tool | tojson }}, all non-ASCII characters (e.g. Chinese
tool descriptions) in the tool schemas get escaped to \uXXXX sequences.

This has two effects for users with Chinese-language MCP/function tools:

  1. Prompt token bloat: token counts roughly double. Reproduced with a real
    request: the same input (one user message + 10 tools with Chinese
    descriptions) was ~3300 tokens with descriptions kept as UTF-8 text, but
    5845 tokens after escaping. BPE tokenization of \uXXXX escapes is far
    less efficient than the original characters.
  2. Degraded comprehension: the model sees escaped gibberish instead of
    readable tool descriptions, hurting function-calling behavior.

Fix

Default ensure_ascii=False in _tojson_compat, matching the transformers
chat template environment. Callers that explicitly pass ensure_ascii=True
still work.

Verification

  • Rendered the same request through both paths:
    • before: 12754 chars / 5835 tokens (escaped)
    • after: 9109 chars / 2993 tokens (UTF-8 text, ~48% reduction)
  • tests/test_template_vars.py passes (15/15).

…loat

Core issue: tojson filter defaulted to ensure_ascii=True, so non-ASCII
characters (e.g. Chinese tool descriptions) were escaped to \uXXXX
sequences. For Qwen3.5 templates rendering tool definitions, this
roughly doubled prompt tokens (5845 vs ~3300 for equivalent input)
and degraded model comprehension of tool descriptions.

Match transformers' template environment by defaulting to
ensure_ascii=False; explicit ensure_ascii=True callers still work.
@Komeiji-Shiki
Komeiji-Shiki force-pushed the fix/template-tojson-ensure-ascii branch from faac60e to 7abdcda Compare August 31, 2026 08:51
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.

1 participant