openai-python icon indicating copy to clipboard operation
openai-python copied to clipboard

Excessive token usage with Cyrillic text in Pydantic schema descriptions due to JSON Unicode escaping

Open tg-bomze opened this issue 1 year ago • 3 comments

TL;DR

If you write the description of structured output parameters not in Latin, but, for example, in Cyrillic (Russian, Kazakh, other languages) or in Chinese, Japanese, and others, a lot of tokens are wasted because non-Latin characters are converted to ASCII when translating json to str. In other words, if I write “Имя пользователя - Том” (in English "Username - Tom") during normal response generation, it consumes 5 tokens, but if I create structured output with the parameter "username" and the description “Имя пользователя” and write “Том” in the prompt, it will consume more than 79 tokens, since json in structured output is sent to the OpenAI server and converted to str without ensure_ascii=False. This is very easy to fix, and it will be very useful for languages that do not use the Latin alphabet.

Confirm this is an issue with the Python library and not an underlying OpenAI API

  • [x] This is an issue with the Python library

Describe the bug

Problem Description

When using Pydantic models with Cyrillic text (or other non-ASCII characters) in field descriptions for structured output with client.beta.chat.completions.parse(), the token count becomes significantly higher than expected due to Unicode escaping in JSON serialization.

Expected vs Actual Token Usage

  • Expected: Cyrillic text should count as UTF-8 encoded characters
  • Actual: Cyrillic characters are converted to Unicode escape sequences (\u0410\u043c\u044f...), dramatically increasing token count

Root Cause Analysis

The issue appears to stem from Python's json.dumps() default behavior of using ensure_ascii=True, which converts non-ASCII characters to Unicode escape sequences. This happens during HTTP request serialization when the Pydantic schema is converted to JSON format for the API request.

import json
from pydantic import BaseModel, Field
from openai import OpenAI

import tiktoken
enc = tiktoken.encoding_for_model("gpt-4o")

user_prompt = "My name John"
messages = [{"role": "user", "content": user_prompt}]

class Schema(BaseModel):
    user_name: str = Field(description="Имя пользователя, если он его называл. Если нет, то оставь пустую строку")

schema = Schema.model_json_schema()

print("--- SCHEMA (ensure_ascii=False) ---")
str_schema = json.dumps(schema, ensure_ascii=False)
num_tokens = len(enc.encode(str_schema))
print(str_schema)
print(f"Num tokens: {num_tokens}")

print("\n--- SCHEMA (ensure_ascii=True) ---")
str_schema = json.dumps(schema, ensure_ascii=True)
num_tokens = len(enc.encode(str_schema))
print(str_schema)
print(f"Num tokens: {num_tokens}")

print("\n--- USER PROMPT ---")
num_tokens = len(enc.encode(user_prompt))
print(user_prompt)
print(f"Num tokens: {num_tokens}")

print("\n--- MESSAGES ---")
str_messages = str(messages)
num_tokens = len(enc.encode(str_messages))
print(str_messages)
print(f"Num tokens: {num_tokens}")

with OpenAI(api_key=api_key) as client:
    response = client.beta.chat.completions.parse(
        model="gpt-4o",
        messages=messages,
        response_format=Schema,
    )

print("\n--- Prompt tokens (from response) ---")
print(f"Num tokens: {response.usage.prompt_tokens}")

Result:

--- SCHEMA (ensure_ascii=False) ---
{"properties": {"user_name": {"description": "Имя пользователя, если он его называл. Если нет, то оставь пустую строку", "title": "User Name", "type": "string"}}, "required": ["user_name"], "title": "Schema", "type": "object"}
Num tokens: 65

--- SCHEMA (ensure_ascii=True) ---
{"properties": {"user_name": {"description": "\u0418\u043c\u044f \u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u044f, \u0435\u0441\u043b\u0438 \u043e\u043d \u0435\u0433\u043e \u043d\u0430\u0437\u044b\u0432\u0430\u043b. \u0415\u0441\u043b\u0438 \u043d\u0435\u0442, \u0442\u043e \u043e\u0441\u0442\u0430\u0432\u044c \u043f\u0443\u0441\u0442\u0443\u044e \u0441\u0442\u0440\u043e\u043a\u0443", "title": "User Name", "type": "string"}}, "required": ["user_name"], "title": "Schema", "type": "object"}
Num tokens: 233

--- USER PROMPT ---
My name John
Num tokens: 3

--- MESSAGES ---
[{'role': 'user', 'content': 'My name John'}]
Num tokens: 16

--- Prompt tokens (from response) ---
Num tokens: 240

Impact

  • Schema with Cyrillic description: 233 tokens (with Unicode escapes)
  • Same schema without escaping would be: 65 tokens
  • 3.6x token overhead for non-ASCII text in schema descriptions

Technical Details

The serialization path appears to be:

  1. Pydantic schema → Python dict
  2. OpenAI client → HTTP request body (JSON serialization)
  3. json.dumps() (default ensure_ascii=True) → Unicode escapes
  4. API server receives escaped version → token counting

Environment

  • openai: 1.91.0
  • pydantic: 2.9.2
  • Python: 3.12.3

This issue affects any usage of structured output with non-ASCII characters in schema descriptions, particularly impacting users working with languages using Cyrillic, Arabic, Chinese, or other non-ASCII scripts.

To Reproduce

Run code snippet

Code snippets

import json
from pydantic import BaseModel, Field
from openai import OpenAI

import tiktoken
enc = tiktoken.encoding_for_model("gpt-4o")

user_prompt = "My name John"
messages = [{"role": "user", "content": user_prompt}]

class Schema(BaseModel):
    user_name: str = Field(description="Имя пользователя, если он его называл. Если нет, то оставь пустую строку")

schema = Schema.model_json_schema()

print("--- SCHEMA (ensure_ascii=False) ---")
str_schema = json.dumps(schema, ensure_ascii=False)
num_tokens = len(enc.encode(str_schema))
print(str_schema)
print(f"Num tokens: {num_tokens}")

print("\n--- SCHEMA (ensure_ascii=True) ---")
str_schema = json.dumps(schema, ensure_ascii=True)
num_tokens = len(enc.encode(str_schema))
print(str_schema)
print(f"Num tokens: {num_tokens}")

print("\n--- USER PROMPT ---")
num_tokens = len(enc.encode(user_prompt))
print(user_prompt)
print(f"Num tokens: {num_tokens}")

print("\n--- MESSAGES ---")
str_messages = str(messages)
num_tokens = len(enc.encode(str_messages))
print(str_messages)
print(f"Num tokens: {num_tokens}")

with OpenAI(api_key=api_key) as client:
    response = client.beta.chat.completions.parse(
        model="gpt-4o",
        messages=messages,
        response_format=Schema,
    )

print("\n--- Prompt tokens (from response) ---")
print(f"Num tokens: {response.usage.prompt_tokens}")

OS

Ubuntu 24.04 LTS

Python version

3.12.3

Library version

1.91.0

tg-bomze avatar Jun 25 '25 20:06 tg-bomze

Update: still reproducible on the newest models (gpt-5.6-terra) and I can now confirm the bug is specific to Structured Outputs, function tools are NOT affected.

1. Structured Outputs still broken. Re-ran the original experiment with gpt-5.6-terra, same result: prompt_tokens = 236, which exactly matches the ASCII-escaped schema (233 tokens for the schema serialized with \uXXXX escapes + 3 tokens for the user message). The same schema serialized as plain UTF-8 is only 65 tokens. So the schema is still being injected into the context in ASCII-escaped form, inflating every non-Latin character ~9x (each Cyrillic letter becomes e.g. \u043f: 6 ASCII chars ≈ 3 tokens instead of ~0.5–1).

2. Function tools works correctly. I ran the same test via function calling: one tool with a single string parameter, identical setup, only the parameter description differs (Russian vs English of equivalent meaning):

  • RU description: prompt_tokens = 148
  • EN description: prompt_tokens = 140

The 8-token difference exactly matches the honest UTF-8 tokenization of the descriptions themselves (o200k_base: 20 tokens for the Russian text vs 12 for the English). If tool definitions were escaped the same way as Structured Outputs schemas, the Russian description would cost 190 tokens and the gap would be ~178 tokens it isn't.

Conclusion: this is not a tokenizer property and not general to all schema injection it's a defect in the Structured Outputs code path specifically. It looks like the schema is serialized with default ASCII escaping (the equivalent of Python's json.dumps(..., ensure_ascii=True)) before being inserted into the prompt, while the tools path serializes as plain UTF-8. Besides the cost, the model actually sees \u0418\u043c\u044f... instead of readable text, which is noise in the context and can hurt instruction following.

tg-bomze avatar Sep 01 '26 12:09 tg-bomze

I rechecked this against the current main (b19c2161b1ea) before considering a duplicate fix. The chat.completions.parse() response-format dictionary is sent through the client JSON serializer, and the current serializer explicitly uses ensure_ascii=False (source).

A direct current-main check with a Pydantic model whose field description is Имя пользователя produced the UTF-8 text in the request body and no \\u0418 escape. This exact client-side reproduction therefore no longer occurs on current main. If the token inflation is still reproducible on the latest released SDK, a captured request body and exact SDK version would help distinguish an older release or a server-side serialization path. I am not opening a duplicate PR while the current client path already has the fix.

Hughhhhcoder avatar Sep 01 '26 16:09 Hughhhhcoder

Thank you for the detailed investigation. The current SDK sends JSON as UTF-8 with ensure_ascii=False; this is also present in the v3.11.0 serializer.

We’re closing the SDK-side serialization report. If excess token usage persists on that version or newer, please comment here with the SDK version, a request ID, and a minimal example so we can reassess. We haven’t verified backend token accounting.

marcuswood-oai avatar Sep 10 '26 16:09 marcuswood-oai