Reservations that price the script: sizing the prompt half of a hold by token rate
- The premise, re-measured on main (0dece8e)
- Why the reference patch in the problem is not enough
- The design
- Evidence
- What this does not fix
- The diff
A reservation is a promise that the hold covers the bill. For an English prompt it does, with room to spare. For every other script it covers a fraction of it, and the difference is written off — not refunded, not billed, simply gone. This patch prices each character at its script’s measured rate when the node sizes a hold, and leaves the English number bit-for-bit where it was.
The premise, re-measured on main (0dece8e)
estimate_prompt_tokens (routstr/payment/helpers.py) divides the whole provider-bound body’s character count by three and calls that a token count. calculate_discounted_max_cost calls it to size the prompt half of the reservation. Measured with tiktoken 0.14, one character is 0.185 cl100k tokens of English prose — so // 3 is a 1.8x ceiling for the language it was measured on. It is a ceiling for no other script:
| script | chars | cl100k tok/char | o200k tok/char |
|---|---|---|---|
| english | 309 | 0.204 | 0.201 |
| chinese | 132 | 1.114 | 0.780 |
| japanese | 145 | 1.028 | 0.759 |
| korean | 154 | 0.948 | 0.597 |
| fullwidth forms | 117 | 1.496 | 1.188 |
| hebrew | 243 | 1.016 | 0.370 |
| greek | 269 | 0.896 | 0.290 |
| arabic | 281 | 0.712 | 0.320 |
| cyrillic | 294 | 0.432 | 0.228 |
| vietnamese | 281 | 0.470 | 0.270 |
| devanagari | 309 | 0.971 | 0.301 |
| bengali | 291 | 1.237 | 0.364 |
| tamil | 337 | 1.350 | 0.353 |
| gujarati | 120 | 1.633 | 0.400 |
| gurmukhi | 130 | 1.615 | 0.554 |
| malayalam | 150 | 1.633 | 0.373 |
| kannada | 146 | 1.767 | 0.390 |
| telugu | 152 | 1.770 | 0.375 |
| sinhala | 170 | 1.824 | 0.541 |
| georgian | 139 | 1.871 | 0.324 |
| armenian | 147 | 1.871 | 0.313 |
| thai | 280 | 1.004 | 0.379 |
| khmer | 178 | 1.674 | 0.646 |
| lao | 126 | 2.127 | 1.802 |
| tibetan | 111 | 2.099 | 1.514 |
| myanmar | 218 | 1.959 | 0.509 |
| amharic | 142 | 2.415 | 1.810 |
| cherokee | 74 | 2.527 | 2.676 |
| emoji | 86 | 2.384 | 1.884 |
| astral ideographs | 44 | 3.000 | 3.000 |
| json (ascii) | 252 | 0.254 | 0.266 |
| base64 (ascii) | 288 | 0.677 | 0.628 |
| hex (ascii) | 96 | 0.458 | 0.458 |
// 3 is 0.333 tokens per character. Every row below the first is under-reserved, by 2.8x for Chinese and 7.9x for Amharic, and routstr/auth.py charges min(chargeable_funds, total_cost) on overrun and writes the shortfall off. A buyer who controls the script of their prompt prices their own hold.
Why the reference patch in the problem is not enough
The problem text carries a proposed solution that puts every non-ASCII BMP character in one class of 4 units (1.333 tok/char), with astral characters at 9. Measured, that class is under its own worst case five times over: Tamil 1.350, fullwidth 1.496, Khmer 1.674, Myanmar 1.959, Amharic 2.415, Cherokee 2.527 — and Cherokee is both encodings’ worst (2.676 on o200k). The astral class’s 9 units (3.0 tok/char) is exactly the rate of astral ideographs, so it has no margin at all.
One class cannot hold nine scripts whose rates differ by 5x. I kept the reference’s two good ideas — a separate estimator, and ASCII untouched — and set the classes from the table above.
The design
Six classes, each weighted in thirds of a token per character so the existing // 3 division stays (and ASCII’s number is unchanged by construction):
| weight | tok/char | class | worst measured member |
|---|---|---|---|
| 1 | 0.333 | ASCII | english 0.204 |
| 2 | 0.667 | Latin with diacritics | vietnamese 0.470 |
| 4 | 1.333 | Greek, Cyrillic, Hebrew, Arabic | hebrew 1.016 |
| 5 | 1.667 | Han, kana, hangul, CJK punctuation, fullwidth | fullwidth 1.496 |
| 6 | 2.000 | Armenian, Indic, Thai, Georgian | georgian/armenian 1.871 |
| 9 | 3.000 | Lao, Tibetan, Myanmar, Ethiopic, Cherokee, Khmer — and every script nobody measured | cherokee 2.676 |
| 10 | 3.333 | astral (in any script) | astral ideographs 3.000 |
Four decisions worth stating:
- The unmeasured default is the highest BMP weight. A script nobody measured is a script nobody proved cheap; the table is evidence for what it contains, not a claim that the rest is cheap.
- The usage estimate is untouched.
estimate_prompt_tokensstill bills a buyer from an estimate when the upstream sends no usage, and there an over-count charges the buyer. The two consumers want opposite errors, so they are two functions. - Over-counting is bounded by construction, not by care. A larger prompt estimate can only shrink the discount; the reservation never rises above
max_cost_for_model. A test holds that line with a 66,000-character CJK body. - ASCII is byte-identical, including the legacy
prompt/inputtoken-id paths, so the traffic that dominates today reserves exactly what it reserved this morning.
The hot path: isascii() is the ASCII fast path (1.4 µs for a 1.2 KB body, vs 1.2 µs before — the difference is two function calls). Non-ASCII bodies are translated through a codepoint→class table in one C-level pass and counted with str.count; a 4 MB CJK body costs 106 ms, a 4 MB mixed body 50 ms, and the table is built once per process in 5 ms. No tokenizer call, no network, no allocation proportional to class count.
Evidence
RED, at the parent 0dece8e, public API only (probe_reservation_script.py, 5 tests, 3F/2P):
E AssertionError: assert 1009.0 >= (1.114 * 3000) # CJK, 3,000 chars
E AssertionError: assert 293.0 >= (2.415 * 852) # Amharic
E AssertionError: assert 239.0 >= (2.384 * 688) # emoji
GREEN, same file, same commit + the patch: 5 passed. The two that pass on both are the controls: the English reservation is unchanged to the millisat, and no reservation exceeds the undiscounted maximum.
Unit tests (tests/unit/test_prompt_reservation_scripts.py, 26 tests): per-script coverage against the measured rates above (12 scripts), ASCII equality against estimate_prompt_tokens on six body shapes, the usage estimate still on // 3, the unmeasured-script default, a per-character walk equivalence over every class boundary ±1 plus mixed and control-character bodies, key weighting, and three call-site tests (calculate_discounted_max_cost) including the acceptance case: 3,000 CJK characters hold 5,000 sats of prompt allowance against 3,342 sats of true cost, where 0dece8e holds 1,009.
Suite: pytest tests/unit = 3,582 passed, 121 skipped, zero failures, on Python 3.14.8. ruff check, ruff format --check, mypy routstr/payment/helpers.py clean.
What this does not fix
- ASCII entropy. Every ASCII character is 0.333 tokens in the class table, but random base64 is 0.677 and hex 0.458. A buyer who sends base64-encoded payloads still under-reserves by ~2x. Fixing it means pricing ASCII at its entropy rather than its script, which changes the English number the problem asked to keep — so it is named here, not smuggled in.
- Per-model tokenizers. The weights cover the worse of cl100k and o200k; a model on a third encoding is covered only insofar as its tokenizer is no denser than those two.
- Sampling. Rates are from samples of 100–340 characters per script, not corpora. Each weight is the smallest third-of-a-token ceiling above the worst measured value, with 11–24% margin on the closest calls (fullwidth 1.496 vs 1.667, cherokee 2.676 vs 3.000), and 0% on none.
- The catalogue. Eleven models whose
max_costdoes not cover their own context window are a different bug (the problem says so too); no prompt estimator can close that.
The diff
Applies clean on 0dece8e (git apply --check verified); source half tblxzm.diff (7,312 B, sha256 6050418885549dd745dabfff96c5c830ab971adb63ffe662bcf5e311c5b302d1), tests half bop80s.diff (19,935 B, sha256 89489d414157747a0e8e49b47b337907f56dc2efd88e2630bbfcc78680b2269b), whole patch s4ddgo.diff (27,247 B, sha256 0c48080a1bda1a9782190bfc7c6b778cde5155580b058019062082bc929eb625) — re-downloaded and compared byte-for-byte after upload.
The probe is a development artifact rather than a test the suite should carry, and is published only with the full patch.
diff --git a/probe_reservation_script.py b/probe_reservation_script.py
new file mode 100644
index 0000000..de9684f
--- /dev/null
+++ b/probe_reservation_script.py
@@ -0,0 +1,115 @@
+"""Probe: does a reservation cover a non-Latin prompt, or a third of it?
+
+Public API only (``calculate_discounted_max_cost``), so it runs unchanged on the
+parent commit and on the fix. Expected: 3 failed / 2 passed at the parent, 5
+passed on the fix. The two that pass at the parent are controls — the English
+number must not move, and over-counting must not exceed the undiscounted
+maximum.
+"""
+
+import os
+
+import pytest
+
+os.environ.setdefault("UPSTREAM_BASE_URL", "http://test")
+os.environ.setdefault("UPSTREAM_API_KEY", "test")
+
+from routstr.core.settings import settings # noqa: E402
+from routstr.payment.helpers import calculate_discounted_max_cost # noqa: E402
+from routstr.payment.models import ( # noqa: E402
+ Architecture,
+ Model,
+ Pricing,
+ TopProvider,
+)
+
+CHINESE = (
+ "节点在为请求预留费用时,会把整段提示的字符数除以三当作词元数。这个比例只对英文成立。"
+ "中文字符在常见分词器下往往一个字符对应一到两个词元,因此预留额度只能覆盖真实成本的三分之一,"
+ "差额被当作容忍度直接抹去。造成的结果是每次请求都在悄悄地赔钱,而且赔的钱随流量线性增长。"
+)
+AMHARIC = (
+ "መስቀለኛው የጥያቄውን ቁጠባ ሲያሰላ የፊደሎቹን ቁጥር በሦስት ይከፍላል እና ውጤቱን እንደ ቶከን ይቆጥራል። "
+ "ይህ ሬሾ ለእንግሊዝኛ ብቻ ትክክል ነው። የአማርኛ ፊደሎች በተለመደው ቶከናይዘር ከሦስት አንድ ቶከን በላይ ይጠቀማሉ።"
+)
+EMOJI = (
+ "😀😃😄😁😆😅🤣😂🙂🙃😉😊😇🥰😍🤩😘😗😚😙🥲😋😛😜🤪😝🤑🤗🤭🤫🤔🤐🤨😐😑😶😏😒🙄😬🤥😌😔😪🤤😴"
+ "😷🤒🤕🤢🤮🤧🥵🥶🥴😵🤯🤠🥳🥸😎🤓🧐😕😟🙁😮😯😲😳🥺😦😧😨😰😥😢😭😱😖😣😞😓😩😫🥱"
+)
+
+MAX_COST_MSATS = 100_000_000
+PROMPT_ALLOWANCE_SATS = 99_000 # model prompt-token limit 100,000 - 1,000
+
+
+def _model() -> Model:
+ return Model(
+ id="m",
+ name="m",
+ created=0,
+ description="",
+ context_length=100_000,
+ architecture=Architecture(
+ modality="text",
+ input_modalities=["text"],
+ output_modalities=["text"],
+ tokenizer="test",
+ instruct_type=None,
+ ),
+ top_provider=TopProvider(context_length=100_000, max_completion_tokens=1_000),
+ pricing=Pricing(prompt=0.01, completion=0.02),
+ sats_pricing=Pricing(
+ prompt=1.0,
+ completion=2.0,
+ max_prompt_cost=100_000.0,
+ max_completion_cost=0.0,
+ max_cost=100_000.0,
+ ),
+ )
+
+
+def _held_sats(reservation_msats: int) -> float:
+ return PROMPT_ALLOWANCE_SATS - (MAX_COST_MSATS - reservation_msats) / 1_000
+
+
+@pytest.fixture(autouse=True)
+def _settings(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(settings, "fixed_pricing", False)
+ monkeypatch.setattr(settings, "min_request_msat", 1)
+ monkeypatch.setattr(settings, "tolerance_percentage", 0)
+
+
+async def test_cjk_prompt_is_covered() -> None:
+ content = (CHINESE * 30)[:3_000]
+ body = {"model": "m", "messages": [{"role": "user", "content": content}]}
+ reservation = await calculate_discounted_max_cost(MAX_COST_MSATS, body, _model())
+ assert _held_sats(reservation) >= 1.114 * len(content)
+
+
+async def test_amharic_prompt_is_covered() -> None:
+ content = (AMHARIC * 6)[:1_000]
+ body = {"model": "m", "messages": [{"role": "user", "content": content}]}
+ reservation = await calculate_discounted_max_cost(MAX_COST_MSATS, body, _model())
+ assert _held_sats(reservation) >= 2.415 * len(content)
+
+
+async def test_emoji_prompt_is_covered() -> None:
+ content = (EMOJI * 8)[:1_000]
+ body = {"model": "m", "messages": [{"role": "user", "content": content}]}
+ reservation = await calculate_discounted_max_cost(MAX_COST_MSATS, body, _model())
+ assert _held_sats(reservation) >= 2.384 * len(content)
+
+
+async def test_english_reservation_is_unchanged() -> None:
+ from routstr.payment.helpers import _sum_string_chars
+
+ body = {"model": "m", "messages": [{"role": "user", "content": "a" * 3_000}]}
+ reservation = await calculate_discounted_max_cost(MAX_COST_MSATS, body, _model())
+ old_tokens = _sum_string_chars(body) // 3
+ assert reservation == MAX_COST_MSATS - (PROMPT_ALLOWANCE_SATS - old_tokens) * 1_000
+
+
+async def test_reservation_stays_under_the_undiscounted_maximum() -> None:
+ """Control: no estimate may reserve more than the model's undiscounted max."""
+ body = {"model": "m", "messages": [{"role": "user", "content": CHINESE * 500}]}
+ reservation = await calculate_discounted_max_cost(MAX_COST_MSATS, body, _model())
+ assert reservation <= MAX_COST_MSATS
diff --git a/routstr/payment/helpers.py b/routstr/payment/helpers.py
index 7f78cd1..a9b70cd 100644
--- a/routstr/payment/helpers.py
+++ b/routstr/payment/helpers.py
@@ -277,8 +277,11 @@ async def calculate_discounted_max_cost(
messages = body.get("messages")
# Estimated over the whole body: a discount driven by message text alone lets
# a caller hide prompt weight elsewhere, shrink the reservation, and be billed
- # for work the reservation never covered.
- prompt_tokens = estimate_prompt_tokens(body)
+ # for work the reservation never covered. Sized by script, not by the English
+ # three-characters-per-token ratio: a CJK or Indic prompt is billed by the
+ # upstream for more tokens than that ratio reserves, and the difference is
+ # written off rather than refunded.
+ prompt_tokens = estimate_prompt_tokens_conservative(body)
# Images are billed as tokens by the upstream but carry no text for
# ``estimate_prompt_tokens`` to count, so they are estimated separately and
@@ -477,6 +480,164 @@ def estimate_prompt_tokens(body: dict) -> int:
)
+# Reservation weights, in thirds of a token per character. ``// 3`` is the
+# English ratio: one character is 0.185 cl100k tokens in prose, so a third of a
+# token is a ceiling with room to spare. It is a ceiling for no other script.
+# Measured with tiktoken 0.14 on both encodings a priced model can use
+# (cl100k_base, o200k_base), worst case per script over samples of ~100-340
+# characters — the higher of the two encodings is what each weight covers:
+#
+# Chinese 1.11, Japanese 1.03, fullwidth forms 1.50, Korean 0.95
+# Greek 0.90, Cyrillic 0.43, Hebrew 1.02, Arabic 0.71
+# Vietnamese and Latin diacritics 0.47
+# Devanagari 0.97, Bengali 1.24, Tamil 1.35, Malayalam 1.63, Gurmukhi 1.62,
+# Gujarati 1.63, Telugu 1.77, Kannada 1.77, Sinhala 1.82, Georgian 1.87,
+# Armenian 1.87, Thai 1.00
+# Khmer 1.67, Lao 2.13, Tibetan 2.10, Myanmar 1.96, Amharic 2.42,
+# Cherokee 2.68
+# emoji 2.38, astral ideographs (CJK ext B) 3.00
+#
+# Scripts nobody measured take the highest measured BMP weight: a script nobody
+# measured is a script nobody proved cheap. Astral characters sit above every
+# BMP weight measured. Each weight is the smallest third-of-a-token ceiling
+# above its class's worst case, so ASCII (weight 1) keeps its number exactly.
+_ASTRAL_WEIGHT = 10
+_UNMEASURED_BMP_WEIGHT = 9
+_RESERVATION_CLASSES: tuple[tuple[int, int, int], ...] = (
+ # Latin with diacritics: Vietnamese, Turkish, Polish, pinyin.
+ (0x00C0, 0x024F, 2),
+ (0x1E00, 0x1EFF, 2),
+ # Greek, Cyrillic, Hebrew, Arabic.
+ (0x0370, 0x03FF, 4),
+ (0x0400, 0x052F, 4),
+ (0x0590, 0x05FF, 4),
+ (0x0600, 0x06FF, 4),
+ (0x0750, 0x077F, 4),
+ (0x08A0, 0x08FF, 4),
+ (0x1F00, 0x1FFF, 4),
+ (0x2DE0, 0x2DFF, 4),
+ (0xA640, 0xA69F, 4),
+ (0xFB1D, 0xFB4F, 4),
+ (0xFB50, 0xFDFF, 4),
+ (0xFE70, 0xFEFF, 4),
+ # Han, kana, hangul, CJK punctuation and fullwidth forms.
+ (0x1100, 0x11FF, 5),
+ (0x2E80, 0x2FDF, 5),
+ (0x3000, 0x303F, 5),
+ (0x3040, 0x30FF, 5),
+ (0x3130, 0x318F, 5),
+ (0x31C0, 0x31EF, 5),
+ (0x3400, 0x4DBF, 5),
+ (0x4E00, 0x9FFF, 5),
+ (0xA960, 0xA97F, 5),
+ (0xAC00, 0xD7FF, 5),
+ (0xF900, 0xFAFF, 5),
+ (0xFE30, 0xFE4F, 5),
+ (0xFF00, 0xFFEF, 5),
+ # Armenian, Indic, Thai, Georgian: measured below 1.9 tokens per character.
+ (0x0530, 0x058F, 6),
+ (0x0900, 0x0DFF, 6),
+ (0x0E00, 0x0E7F, 6),
+ (0x10A0, 0x10FF, 6),
+ (0x1C90, 0x1CBF, 6),
+ (0xFB13, 0xFB17, 6),
+ # Measured above 1.9: Lao, Tibetan, Myanmar, Ethiopic, Cherokee, Khmer.
+ (0x0E80, 0x0EFF, 9),
+ (0x0F00, 0x0FFF, 9),
+ (0x1000, 0x109F, 9),
+ (0x1200, 0x139F, 9),
+ (0x13A0, 0x13FF, 9),
+ (0x1780, 0x17FF, 9),
+ (0x19E0, 0x19FF, 9),
+ (0x2D80, 0x2DDF, 9),
+ (0xAB00, 0xAB2F, 9),
+)
+
+# One marker per weight, all control characters: ``str.translate`` maps every
+# non-ASCII BMP character to its class marker in one pass, and the counts then
+# come from ``str.count``. A body that contains a control character of the same
+# value would be counted as that class *as well* — the direction that can only
+# raise an estimate, never lower it.
+_MARKER_WEIGHTS: dict[str, int] = {
+ "\x01": 2,
+ "\x02": 4,
+ "\x03": 5,
+ "\x04": 6,
+ "\x05": 9,
+}
+_bmp_markers: dict[int, str] | None = None
+
+
+def _character_weight(codepoint: int) -> int:
+ """Weight of one character, in thirds of a token."""
+ if codepoint < 0x80:
+ return 1
+ if codepoint > 0xFFFF:
+ return _ASTRAL_WEIGHT
+ for low, high, weight in _RESERVATION_CLASSES:
+ if low <= codepoint <= high:
+ return weight
+ return _UNMEASURED_BMP_WEIGHT
+
+
+def _reservation_marker_table() -> dict[int, str]:
+ """Codepoint-to-marker table, built once per process on first non-ASCII body."""
+ global _bmp_markers
+ if _bmp_markers is None:
+ table = {cp: "\x05" for cp in range(0x80, 0x10000)}
+ for low, high, weight in _RESERVATION_CLASSES:
+ marker = next(m for m, w in _MARKER_WEIGHTS.items() if w == weight)
+ for cp in range(low, high + 1):
+ table[cp] = marker
+ _bmp_markers = table
+ return _bmp_markers
+
+
+def _string_units(text: str) -> int:
+ """Weight of one string, in thirds of a token, by script."""
+ if text.isascii():
+ return len(text)
+ markers = text.translate(_reservation_marker_table())
+ # Every BMP character is now an ASCII marker, so whatever is still
+ # non-ASCII is astral.
+ astral = len(markers) - len(markers.encode("ascii", "ignore"))
+ units = len(text) + (_ASTRAL_WEIGHT - 1) * astral
+ for marker, weight in _MARKER_WEIGHTS.items():
+ units += (weight - 1) * markers.count(marker)
+ return units
+
+
+def _sum_string_units(node: Any) -> int:
+ """Recursively sum the weight of every string in the tree, keys included."""
+ if isinstance(node, str):
+ return _string_units(node)
+ if isinstance(node, dict):
+ return sum(
+ _string_units(str(key)) + _sum_string_units(value)
+ for key, value in node.items()
+ )
+ if isinstance(node, list):
+ return sum(_sum_string_units(item) for item in node)
+ return 0
+
+
+def estimate_prompt_tokens_conservative(body: dict) -> int:
+ """Estimate prompt tokens for a reservation, pricing each script at its rate.
+
+ ``estimate_prompt_tokens`` divides characters by three, which is the English
+ ratio; a reservation sized from it covers a third of a Chinese, Tamil or
+ Amharic prompt and the node writes off the rest. This estimate prices each
+ character at the highest measured rate of its script class instead, and the
+ two are deliberately separate: the reservation must never under-count, while
+ the usage estimate that bills a buyer must not over-count.
+ """
+ return (
+ _sum_string_units(body) // 3
+ + _count_prompt_token_ids(body.get("prompt"))
+ + _count_prompt_token_ids(body.get("input"))
+ )
+
+
IMAGE_FETCH_TIMEOUT_SECONDS = 10.0
# Dimensions live in the header, so a prefix suffices and an endless body cannot
# pin memory.
diff --git a/tests/unit/test_prompt_reservation_scripts.py b/tests/unit/test_prompt_reservation_scripts.py
new file mode 100644
index 0000000..ff2057a
--- /dev/null
+++ b/tests/unit/test_prompt_reservation_scripts.py
@@ -0,0 +1,272 @@
+"""The reservation prices the script, not the English three-characters-per-token ratio.
+
+Rates in ``MEASURED`` are tokens per character, measured with tiktoken 0.14 on
+``cl100k_base`` and ``o200k_base`` (the higher of the two), on the sample text
+embedded beside each entry. The estimator must cover the higher of them.
+"""
+
+import os
+
+import pytest
+
+os.environ.setdefault("UPSTREAM_BASE_URL", "http://test")
+os.environ.setdefault("UPSTREAM_API_KEY", "test")
+
+from routstr.core.settings import settings # noqa: E402
+from routstr.payment.helpers import ( # noqa: E402
+ _character_weight,
+ _string_units,
+ _sum_string_units,
+ calculate_discounted_max_cost,
+ estimate_prompt_tokens,
+ estimate_prompt_tokens_conservative,
+)
+from routstr.payment.models import ( # noqa: E402
+ Architecture,
+ Model,
+ Pricing,
+ TopProvider,
+)
+
+CHINESE = (
+ "节点在为请求预留费用时,会把整段提示的字符数除以三当作词元数。这个比例只对英文成立。"
+ "中文字符在常见分词器下往往一个字符对应一到两个词元,因此预留额度只能覆盖真实成本的三分之一,"
+ "差额被当作容忍度直接抹去。造成的结果是每次请求都在悄悄地赔钱,而且赔的钱随流量线性增长。"
+)
+JAPANESE = (
+ "ノードはリクエストの予約額を計算するとき、プロンプト全体の文字数を三で割ってトークン数とみなします。"
+ "この比率は英語にしか当てはまりません。日本語の文字は一般的なトークナイザでは一文字あたり一トークン以上になり、"
+ "予約は実際の費用の三分の一しか覆いません。差額は許容誤差として帳消しにされます。"
+)
+KOREAN = (
+ "노드는 요청을 예약할 때 프롬프트 전체의 문자 수를 삼으로 나누어 토큰 수로 추정합니다. "
+ "이 비율은 영어에서만 성립합니다. 한국어 문자는 일반적인 토크나이저에서 한 글자에 한 토큰 이상이 되므로 "
+ "예약 금액은 실제 비용의 삼분의 일만 감당합니다. 차액은 허용 오차로 지워집니다."
+)
+ARABIC = (
+ "تحسب العقدة تكلفة الحجز بقسمة عدد المحارف في الطلب على ثلاثة، ثم تعتبر الناتج عددا من الرموز. "
+ "هذه النسبة صحيحة للغة الإنجليزية وحدها. الحروف العربية تستهلك في المُرمِّز الشائع أكثر من ثلث رمز لكل محرف، "
+ "لذلك يغطي الحجز جزءا من التكلفة الحقيقية فقط، ويُشطب الفرق باعتباره هامش تسامح."
+)
+DEVANAGARI = (
+ "नोड अनुरोध का आरक्षण करते समय पूरे संदेश के अक्षरों की संख्या को तीन से भाग देकर टोकन मान लेता है। "
+ "यह अनुपात केवल अंग्रेज़ी के लिए सही है। देवनागरी अक्षर सामान्य टोकनाइज़र में प्रति अक्षर एक तिहाई से अधिक टोकन लेते हैं, "
+ "इसलिए आरक्षण वास्तविक लागत का केवल एक हिस्सा ही ढकता है और बाकी अंतर माफ कर दिया जाता है।"
+)
+TAMIL = (
+ "முனையம் கோரிக்கைக்கான ஒதுக்கீட்டைக் கணக்கிடும் போது செய்தியின் எழுத்தெண்ணிக்கையை மூன்றால் வகுத்து டோக்கனாகக் கருதுகிறது. "
+ "இந்த விகிதம் ஆங்கிலத்துக்கு மட்டுமே பொருந்தும். தமிழ் எழுத்துகள் பொதுவான டோக்கனைசரில் ஒரு எழுத்துக்கு மூன்றில் ஒரு பங்கை விட அதிக டோக்கன் எடுக்கின்றன, "
+ "எனவே ஒதுக்கீடு உண்மையான செலவின் ஒரு பகுதியை மட்டுமே ஈடுசெய்கிறது."
+)
+KHMER = (
+ "ថ្នាំងគណនាប្រាក់បម្រុងដោយចែកចំនួនតួអក្សរនៃសំណើនឹងបី ហើយចាត់ទុកថាជាចំនួនថូខឹន។ "
+ "សមាមាត្រនេះត្រឹមត្រូវសម្រាប់ភាសាអង់គ្លេសតែប៉ុណ្ណោះ។ តួអក្សរខ្មែរប្រើថូខឹនច្រើនជាងមួយភាគបីក្នុងមួយតួ។"
+)
+MYANMAR = (
+ "ဆုံမှတ်သည် တောင်းဆိုချက်၏ စာလုံးအရေအတွက်ကို သုံးဖြင့်စားပြီး တိုကင်အရေအတွက်အဖြစ် သတ်မှတ်သည်။ "
+ "ဤအချိုးသည် အင်္ဂလိပ်စာအတွက်သာ မှန်ကန်သည်။ မြန်မာစာလုံးများသည် သာမန်တိုကင်ခွဲစက်တွင် တစ်လုံးလျှင် သုံးပုံတစ်ပုံထက် ပိုသုံးသည်။"
+)
+AMHARIC = (
+ "መስቀለኛው የጥያቄውን ቁጠባ ሲያሰላ የፊደሎቹን ቁጥር በሦስት ይከፍላል እና ውጤቱን እንደ ቶከን ይቆጥራል። "
+ "ይህ ሬሾ ለእንግሊዝኛ ብቻ ትክክል ነው። የአማርኛ ፊደሎች በተለመደው ቶከናይዘር ከሦስት አንድ ቶከን በላይ ይጠቀማሉ።"
+)
+FULLWIDTH = (
+ "The node bills the buyer for the tokens and reserves before the call."
+ "全角文字はASCIIと同じ意味でも別の符号位置であり、文字数を数えるだけでは重さを捉えられない。"
+)
+EMOJI = (
+ "😀😃😄😁😆😅🤣😂🙂🙃😉😊😇🥰😍🤩😘😗😚😙🥲😋😛😜🤪😝🤑🤗🤭🤫🤔🤐🤨😐😑😶😏😒🙄😬🤥😌😔😪🤤😴"
+ "😷🤒🤕🤢🤮🤧🥵🥶🥴😵🤯🤠🥳🥸😎🤓🧐😕😟🙁😮😯😲😳🥺😦😧😨😰😥😢😭😱😖😣😞😓😩😫🥱"
+)
+ASTRAL_IDEOGRAPHS = "𠀀𠀁𠀂𠀃𠀄𠀅𠀆𠀇𠀈𠀉𠀊𠀋𠀌𠀍𠀎𠀏𠀐𠀑𠀒𠀓𠀔𠀕𠀖𠀗𠀘𠀙𠀚𠀛𠀜𠀝𠀞𠀟"
+
+# script -> (sample, measured tokens per character)
+MEASURED = {
+ "chinese": (CHINESE, 1.114),
+ "japanese": (JAPANESE, 1.028),
+ "korean": (KOREAN, 0.948),
+ "arabic": (ARABIC, 0.712),
+ "devanagari": (DEVANAGARI, 0.971),
+ "tamil": (TAMIL, 1.350),
+ "khmer": (KHMER, 1.674),
+ "myanmar": (MYANMAR, 1.959),
+ "amharic": (AMHARIC, 2.415),
+ "fullwidth": (FULLWIDTH, 1.496),
+ "emoji": (EMOJI, 2.384),
+ "astral_ideographs": (ASTRAL_IDEOGRAPHS, 3.000),
+}
+
+
+def _model(
+ *,
+ prompt: float = 1.0,
+ completion: float = 2.0,
+ max_prompt_cost: float = 100_000.0,
+ max_completion_cost: float = 0.0,
+ max_cost: float = 100_000.0,
+ context_length: int = 100_000,
+ max_completion_tokens: int = 1_000,
+) -> Model:
+ return Model(
+ id="m",
+ name="m",
+ created=0,
+ description="",
+ context_length=context_length,
+ architecture=Architecture(
+ modality="text",
+ input_modalities=["text"],
+ output_modalities=["text"],
+ tokenizer="test",
+ instruct_type=None,
+ ),
+ top_provider=TopProvider(
+ context_length=context_length,
+ max_completion_tokens=max_completion_tokens,
+ ),
+ pricing=Pricing(prompt=0.01, completion=0.02),
+ sats_pricing=Pricing(
+ prompt=prompt,
+ completion=completion,
+ max_prompt_cost=max_prompt_cost,
+ max_completion_cost=max_completion_cost,
+ max_cost=max_cost,
+ ),
+ )
+
+
+@pytest.mark.parametrize("script", sorted(MEASURED))
+def test_reservation_weight_covers_the_measured_token_rate(script: str) -> None:
+ sample, rate = MEASURED[script]
+ reserved_tokens = _string_units(sample) / 3
+ assert reserved_tokens >= rate * len(sample)
+
+
+@pytest.mark.parametrize(
+ "body",
+ [
+ {"messages": [{"role": "user", "content": "hello there"}]},
+ {"messages": [{"role": "user", "content": "a" * 3_000}], "max_tokens": 10},
+ {"prompt": [[1, 2], [3, 4, 5]]},
+ {"input": [1234, 5678], "model": "m"},
+ {"tools": [{"type": "function", "data": "x" * 1_000}]},
+ {},
+ ],
+)
+def test_ascii_bodies_estimate_exactly_as_before(body: dict) -> None:
+ """The English body reserves the number it always reserved."""
+ assert estimate_prompt_tokens_conservative(body) == estimate_prompt_tokens(body)
+
+
+def test_usage_estimate_keeps_the_english_ratio() -> None:
+ """The estimate that bills a buyer is not the reservation's estimate."""
+ from routstr.payment.helpers import _sum_string_chars
+
+ body = {"messages": [{"content": CHINESE}]}
+ assert estimate_prompt_tokens(body) == _sum_string_chars(body) // 3
+ assert estimate_prompt_tokens_conservative(body) > estimate_prompt_tokens(body)
+
+
+def test_unmeasured_script_takes_the_highest_bmp_weight() -> None:
+ # U+2600 (miscellaneous symbols) is in no measured class.
+ assert _character_weight(0x2600) == 9
+ assert _string_units("\u2600" * 300) == 300 * 9
+ # Astral characters sit above every BMP weight.
+ assert _character_weight(0x1F600) == 10
+ assert _character_weight(0x4E00) == 5
+ assert _character_weight(0x41) == 1
+
+
+def test_fast_path_matches_a_per_character_walk() -> None:
+ """Every class boundary, and mixed bodies, agree with the plain walk."""
+ samples = [text for text, _ in MEASURED.values()]
+ samples += [
+ "plain ascii",
+ "mixed 中文 and عربى and 😀 astral 𠀀 here",
+ "control \x01\x02\x03\x05 markers",
+ "é" * 40 + "ж" * 40 + "字" * 40,
+ ]
+ boundaries: list[str] = []
+ for low, high, _weight in (
+ (0x00C0, 0x024F, 2),
+ (0x0370, 0x03FF, 4),
+ (0x4E00, 0x9FFF, 5),
+ (0x0900, 0x0DFF, 6),
+ (0x13A0, 0x13FF, 9),
+ ):
+ for cp in (low - 1, low, high, high + 1):
+ boundaries.append(chr(cp))
+ samples.append("".join(boundaries))
+
+ for sample in samples:
+ expected = sum(_character_weight(ord(char)) for char in sample)
+ assert _string_units(sample) == expected
+
+
+def test_control_characters_cannot_lower_the_estimate() -> None:
+ """A body that looks like a class marker is over-counted, never under-counted."""
+ # 5 + 5 + 1 is the honest weight; the collision adds, it cannot subtract.
+ assert _string_units("节点\x05") >= 2 * 5 + 1
+
+
+def test_body_keys_are_weighted_by_script_too() -> None:
+ assert _sum_string_units({"节点": "x"}) == 2 * 5 + 1
+
+
+async def test_reservation_covers_the_true_prompt_cost_of_3000_cjk_characters(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Acceptance test from the problem: 455 msats today, 1,320 msats of cost."""
+ monkeypatch.setattr(settings, "fixed_pricing", False)
+ monkeypatch.setattr(settings, "min_request_msat", 1)
+ monkeypatch.setattr(settings, "tolerance_percentage", 0)
+ model = _model()
+ content = (CHINESE * 30)[:3_000]
+ body = {"model": "m", "messages": [{"role": "user", "content": content}]}
+ chars = len(content)
+ true_tokens = 1.114 * chars # cl100k rate, the same sample
+
+ reservation = await calculate_discounted_max_cost(100_000_000, body, model)
+
+ # The reservation's prompt half is what it holds for the prompt; the whole
+ # reservation must at least cover the tokens the upstream will bill for.
+ held_sats = 100_000 - (100_000_000 - reservation) / 1_000
+ assert held_sats >= true_tokens
+
+
+async def test_same_length_prompts_reserve_by_script(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(settings, "fixed_pricing", False)
+ monkeypatch.setattr(settings, "min_request_msat", 1)
+ monkeypatch.setattr(settings, "tolerance_percentage", 0)
+ model = _model()
+ english = {"messages": [{"role": "user", "content": "a" * 3_000}], "model": "m"}
+ chinese = {"messages": [{"role": "user", "content": CHINESE * 6}], "model": "m"}
+ emoji = {"messages": [{"role": "user", "content": EMOJI * 8}], "model": "m"}
+
+ ascii_reservation = await calculate_discounted_max_cost(100_000_000, english, model)
+ cjk_reservation = await calculate_discounted_max_cost(100_000_000, chinese, model)
+ emoji_reservation = await calculate_discounted_max_cost(100_000_000, emoji, model)
+
+ english_tokens = estimate_prompt_tokens(english)
+ # The prompt allowance is the model's prompt-token limit (100,000 - 1,000).
+ allowance_sats = 99_000
+ assert ascii_reservation == 100_000_000 - (allowance_sats - english_tokens) * 1_000
+ assert cjk_reservation > ascii_reservation
+ assert emoji_reservation > ascii_reservation
+
+
+async def test_reservation_never_exceeds_the_undiscounted_max_cost(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Over-counting removes at most the discount; it cannot reserve more."""
+ monkeypatch.setattr(settings, "fixed_pricing", False)
+ monkeypatch.setattr(settings, "min_request_msat", 1)
+ monkeypatch.setattr(settings, "tolerance_percentage", 0)
+ model = _model()
+ body = {"model": "m", "messages": [{"role": "user", "content": CHINESE * 500}]}
+
+ reservation = await calculate_discounted_max_cost(100_000_000, body, model)
+
+ assert reservation == 100_000_000
Write a comment