mirror of
https://github.com/hasso5703/alzeo.git
synced 2026-12-05 12:24:28 +01:00
The engine's count routes take no Responses input items, so the body's size decided, a token a byte where a wedge is possible: on the 27B's 1M window a Codex session of 820 kB, about 200,000 tokens, was refused as "about ~820044 tokens", where 2.5 MB of the same text passed on /v1/chat/completions (Codex 0.144.4, 2026-11-30). Its JSON text is counted, its media priced apart: with the 27B's tokenizer and chat template, a Codex request and ten made from it (code, French, Chinese, digits, emoji, 120 tools) are counted at or above the rendered prompt, 1.0 to 2.0 times it, 8 on tabs and blank lines. A request the engine holds a part of (an earlier response, an item by its id) is judged by its size, as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
153 lines
7.3 KiB
Python
153 lines
7.3 KiB
Python
"""A /v1/responses prompt is counted by the engine, as a chat's is (v6.63).
|
|
|
|
The engine's count routes take no Responses input items, so the body's size decided: a token a byte where a
|
|
wedge is possible. On the 27B's 1M window, 820 kB of prose (about 200,000 tokens) were refused as "about
|
|
~820044 tokens", where 2.5 MB of it passed on /v1/chat/completions (2026-11-30)."""
|
|
import base64
|
|
import http.server
|
|
import importlib.util
|
|
import json
|
|
import os
|
|
import struct
|
|
import sys
|
|
import threading
|
|
import time
|
|
import unittest
|
|
import urllib.error
|
|
import urllib.request
|
|
from pathlib import Path
|
|
|
|
REPO = Path(__file__).resolve().parents[1]
|
|
KEY = "k3y-of-this-test-0123456789"
|
|
PROSE = "The quick brown fox jumps over the lazy dog. " * 100_000 # 4.5 MB
|
|
|
|
|
|
def png(w, h):
|
|
return base64.b64encode(b"\x89PNG\r\n\x1a\n" + struct.pack(">I4sIIBBBBB", 13, b"IHDR", w, h, 8, 2, 0, 0, 0) + b"\0" * 900_000).decode()
|
|
|
|
|
|
class Engine(http.server.BaseHTTPRequestHandler):
|
|
"""One token every four characters, of whatever /tokenize is asked."""
|
|
protocol_version = "HTTP/1.1"
|
|
counted, generated = [], []
|
|
|
|
def log_message(self, *a):
|
|
pass
|
|
|
|
def do_POST(self):
|
|
raw = self.rfile.read(int(self.headers.get("Content-Length") or 0))
|
|
out = {}
|
|
if self.path == "/tokenize":
|
|
prompt = json.loads(raw)["prompt"]
|
|
self.counted.append(prompt)
|
|
out = {"count": len(prompt) // 4}
|
|
else:
|
|
self.generated.append(self.path)
|
|
body = json.dumps(out).encode()
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(body)))
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
|
|
|
|
class AResponsesPromptIsCounted(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
saved = dict(os.environ)
|
|
cls.addClassCleanup(lambda: (os.environ.clear(), os.environ.update(saved)))
|
|
cls.engine = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Engine)
|
|
cls.engine.daemon_threads = True
|
|
threading.Thread(target=cls.engine.serve_forever, daemon=True).start()
|
|
cls.addClassCleanup(cls.engine.server_close)
|
|
cls.addClassCleanup(cls.engine.shutdown)
|
|
for k in ("QWEN38_CLIENT_KEYS_FILE", "PROMPT_CEILING_TOKENS", "FLASH_PROMPT_CEILING_TOKENS"):
|
|
os.environ.pop(k, None)
|
|
os.environ.update(UPSTREAM=f"http://127.0.0.1:{cls.engine.server_port}", PROXY_HOLD_UNITS="", QWEN38_UPSTREAM_API_KEY=KEY)
|
|
spec = importlib.util.spec_from_file_location(f"kp_resp_{time.time_ns()}", REPO / "keepalive-proxy.py")
|
|
cls.mod = importlib.util.module_from_spec(spec)
|
|
sys.argv = ["keepalive-proxy.py"]
|
|
spec.loader.exec_module(cls.mod)
|
|
cls.mod.log = lambda msg: None
|
|
cls.mod._api_key = lambda: KEY
|
|
cls.proxy = cls.mod.Server(("127.0.0.1", 0), cls.mod.H)
|
|
threading.Thread(target=cls.proxy.serve_forever, daemon=True).start()
|
|
cls.addClassCleanup(cls.proxy.server_close)
|
|
cls.addClassCleanup(cls.proxy.shutdown)
|
|
|
|
def setUp(self):
|
|
Engine.counted.clear()
|
|
Engine.generated.clear()
|
|
# the 27B's 1M window: past the 794,552 usable, where a wedge is possible
|
|
self.mod._POOL.update(tokens=863_644, window=863_638, ts=time.time())
|
|
self.mod._SERVED.update(names=("qwen3.8-27b",), engine="sglang", ts=time.time())
|
|
|
|
def ask(self, doc, path="/v1/responses"):
|
|
req = urllib.request.Request(f"http://127.0.0.1:{self.proxy.server_address[1]}{path}", data=json.dumps(doc).encode(),
|
|
headers={"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"})
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=20) as r:
|
|
return r.status, r.read().decode()
|
|
except urllib.error.HTTPError as e:
|
|
return e.code, e.read().decode()
|
|
|
|
@staticmethod
|
|
def message(*parts, role="user"):
|
|
return {"type": "message", "role": role, "content": list(parts)}
|
|
|
|
def test_what_fits_is_relayed_as_on_the_chat_route(self):
|
|
for size in (820_000, 1_000_000, 2_500_000):
|
|
for given in (PROSE[:size], [self.message({"type": "input_text", "text": PROSE[:size]})]):
|
|
Engine.counted.clear()
|
|
status, raw = self.ask({"model": "m", "instructions": "Be short.", "input": given, "stream": False})
|
|
self.assertEqual(status, 200, raw[:200])
|
|
self.assertIn(PROSE[:size], Engine.counted[0])
|
|
self.assertIn("Be short.", Engine.counted[0])
|
|
self.assertEqual(len(Engine.generated), 6)
|
|
|
|
def test_what_does_not_is_refused_on_the_engine_s_count(self):
|
|
status, raw = self.ask({"model": "m", "input": PROSE[:3_900_000]})
|
|
self.assertEqual(status, 400)
|
|
self.assertIn("prompt tokens (counted by the engine)", raw)
|
|
self.assertIn("context_length_exceeded", raw)
|
|
self.assertEqual(Engine.generated, [])
|
|
|
|
def test_its_tools_and_its_tool_results_are_counted(self):
|
|
self.ask({"model": "m", "input": [self.message({"type": "input_text", "text": PROSE[:900_000]}),
|
|
{"type": "function_call", "call_id": "c", "name": "sh", "arguments": "{\"a\": 1}"},
|
|
{"type": "function_call_output", "call_id": "c", "output": "THE-OUTPUT"}],
|
|
"tools": [{"type": "function", "name": "THE-TOOL", "parameters": {"type": "object"}}]})
|
|
self.assertIn("THE-OUTPUT", Engine.counted[0])
|
|
self.assertEqual(Engine.counted[0].count("THE-TOOL"), 2, "what the template writes around a tool is more than its JSON")
|
|
|
|
def test_its_images_are_priced_and_left_out_of_the_text(self):
|
|
data = png(1000, 1000)
|
|
image = {"type": "input_image", "image_url": f"data:image/png;base64,{data}"}
|
|
media = [0]
|
|
for j in ({"input": [self.message(image)]}, {"input": [{"type": "function_call_output", "call_id": "c", "output": [image]}]},
|
|
{"input": [self.message({"type": "input_image", "image_url": {"url": data}})]}):
|
|
media[0] = 0
|
|
text = self.mod.responses_text(j, media)
|
|
self.assertNotIn(data[:100], text)
|
|
self.assertEqual(media[0], self.mod._image_tokens(1000, 1000) + self.mod.RESPONSES_OVERHEAD + self.mod.RESPONSES_ITEM)
|
|
status, raw = self.ask({"model": "m", "input": [self.message(image, {"type": "input_text", "text": "what is it?"})]})
|
|
self.assertEqual(status, 200, raw[:200])
|
|
self.assertLess(len(Engine.counted[0]), 1000)
|
|
|
|
def test_a_prompt_the_engine_holds_a_part_of_is_judged_by_its_size(self):
|
|
big = [self.message({"type": "input_text", "text": PROSE[:900_000]})]
|
|
for doc in ({"input": big, "previous_response_id": "resp_1"}, {"input": big, "conversation": "conv_1"},
|
|
{"input": [*big, {"type": "item_reference", "id": "i"}]}):
|
|
status, raw = self.ask({"model": "m", **doc})
|
|
self.assertEqual(status, 400, raw[:200])
|
|
self.assertIn("by size", raw)
|
|
self.assertEqual(Engine.counted, [])
|
|
|
|
def test_a_shape_it_cannot_read_is_judged_by_its_size(self):
|
|
for doc in ({"input": None, "x": PROSE[:900_000]}, {"x": PROSE[:900_000]}):
|
|
self.assertEqual(self.ask({"model": "m", **doc})[0], 400)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|