Files
alzeo/tests/test_proxy_thinking_display.py

173 lines
8.3 KiB
Python

#!/usr/bin/env python3
"""A Claude Code session's requests are served at their first try (proxy v6.68).
Claude Code in a session asks its thinking displayed as "updates" (2.1.330, 2026-12-01). SGLang knows two values before
1.0.0 and answers 400 to a third, on the generation and on its count route: Claude Code asked again without it, so two
requests of every session were refused, and this proxy's own count of their prompts with them. The engine here refuses as
SGLang 0.5.22 does (AnthropicThinkingParam, its protocol.py)."""
import http.server
import importlib.util
import json
import os
import socket
import sys
import threading
import time
import unittest
from pathlib import Path
REPO = Path(__file__).resolve().parents[1]
KEY = "k3y-of-this-test-0123456789"
SAID = "请用中文回答 😀 about \"updates\" and \"display\""
class Engine(http.server.BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
seen = []
def log_message(self, *a):
pass
def do_POST(self):
raw = self.rfile.read(int(self.headers.get("Content-Length") or 0))
self.seen.append((self.path, raw))
display = (json.loads(raw).get("thinking") or {}).get("display")
code, out = 200, b'{"input_tokens": 7}'
if display not in (None, "summarized", "omitted"):
code, out = 400, b'{"type": "error", "error": {"type": "invalid_request_error", "message": "thinking.display"}}'
elif self.path == "/v1/messages":
out = json.dumps({"type": "message", "role": "assistant", "content": [{"type": "text", "text": "ok"}],
"usage": {"input_tokens": 7, "output_tokens": 1}}).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(out)))
self.end_headers()
self.wfile.write(out)
class ThroughTheProxy(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)
os.environ.pop("QWEN38_CLIENT_KEYS_FILE", None)
os.environ.update(UPSTREAM=f"http://127.0.0.1:{cls.engine.server_port}", CLIENT_IO_S="5", PROMPT_CEILING_TOKENS="0",
PROXY_HOLD_UNITS="", QWEN38_UPSTREAM_API_KEY=KEY)
spec = importlib.util.spec_from_file_location(f"kp_display_{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.journal = []
cls.mod.log = cls.journal.append
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.seen.clear()
self.journal.clear()
self.mod._display_logged = self.mod._LoggedOnce()
self.serve("sglang")
def serve(self, engine):
self.mod._SERVED.update(names=("qwen3.8-27b",), engine=engine, ts=time.time())
self.mod._POOL.update(tokens=10_000_000, window=1000, ts=time.time())
def ask(self, thinking, path="/v1/messages", **more):
"""(the status the client got, what the engine was sent on that path)"""
Engine.seen.clear()
doc = {"model": "qwen3.8-27b", "max_tokens": 5, "messages": [{"role": "user", "content": SAID}], **more}
if thinking is not None:
doc["thinking"] = thinking
body = json.dumps(doc, ensure_ascii=False).encode()
s = socket.create_connection(("127.0.0.1", self.proxy.server_address[1]), timeout=8)
got = b""
try:
s.sendall(f"POST {path} HTTP/1.1\r\nHost: p\r\nContent-Type: application/json\r\nAuthorization: Bearer {KEY}\r\n"
f"Content-Length: {len(body)}\r\nConnection: close\r\n\r\n".encode() + body)
while True:
chunk = s.recv(65536)
if not chunk:
break
got += chunk
finally:
s.close()
return int(got.split(b" ", 2)[1]), [raw for p, raw in Engine.seen if p == path], body
def test_a_session_is_served_at_its_first_try(self):
status, sent, _ = self.ask({"type": "adaptive", "display": "updates"})
self.assertEqual(status, 200)
self.assertEqual([json.loads(raw)["thinking"] for raw in sent], [{"type": "adaptive"}], "asked once, as Claude Code asks it again")
def test_so_is_the_count_of_its_prompt(self):
status, sent, _ = self.ask({"type": "adaptive", "display": "updates"}, path="/v1/messages/count_tokens")
self.assertEqual(status, 200)
self.assertEqual(json.loads(sent[-1])["thinking"], {"type": "adaptive"})
def test_the_rest_of_the_request_is_what_the_client_sent(self):
_, sent, _ = self.ask({"type": "enabled", "budget_tokens": 4096, "display": "updates"}, system="s", temperature=0.5)
doc = json.loads(sent[0])
self.assertEqual(doc["thinking"], {"type": "enabled", "budget_tokens": 4096})
self.assertEqual((doc["messages"], doc["system"], doc["temperature"], doc["max_tokens"]),
([{"role": "user", "content": SAID}], "s", 0.5, 5))
self.assertIn("请用中文回答".encode(), sent[0], "its text stays UTF-8")
def test_the_values_sglang_takes_go_byte_for_byte(self):
for thinking in ({"type": "adaptive", "display": "omitted"}, {"type": "adaptive", "display": "summarized"},
{"type": "adaptive"}, {"type": "disabled"}, None):
with self.subTest(thinking=thinking):
status, sent, body = self.ask(thinking)
self.assertEqual((status, sent), (200, [body]))
def test_another_engine_gets_it_as_it_came(self):
for engine in ("vllm", "llamacpp"):
with self.subTest(engine=engine):
self.serve(engine)
_, sent, body = self.ask({"type": "adaptive", "display": "updates"})
self.assertEqual(sent, [body])
def test_it_is_said_once(self):
for _ in range(3):
self.ask({"type": "adaptive", "display": "updates"})
self.assertEqual(len([x for x in self.journal if "thinking.display updates" in x]), 1)
class TheFunction(unittest.TestCase):
@classmethod
def setUpClass(cls):
saved = dict(os.environ)
cls.addClassCleanup(lambda: (os.environ.clear(), os.environ.update(saved)))
os.environ.update(UPSTREAM="http://127.0.0.1:9", PROXY_HOLD_UNITS="")
spec = importlib.util.spec_from_file_location("kp_display_fn", REPO / "keepalive-proxy.py")
cls.kp = importlib.util.module_from_spec(spec)
sys.argv = ["keepalive-proxy.py"]
spec.loader.exec_module(cls.kp)
def setUp(self):
self.kp._SERVED.update(names=(), engine="", ts=0.0)
def test_before_the_engine_is_known_too(self):
raw = json.dumps({"thinking": {"type": "adaptive", "display": "updates"}}).encode()
self.assertEqual(json.loads(self.kp.thinking_display(raw, "/v1/messages?beta=true")[0]), {"thinking": {"type": "adaptive"}})
def test_on_a_doubt_it_is_not_touched(self):
updates = json.dumps({"thinking": {"type": "adaptive", "display": "updates"}}).encode()
for raw, path in ((updates, "/v1/chat/completions"), (updates, "/v1/messages/batches"), (b"", "/v1/messages"),
(None, "/v1/messages"), (updates[:-3] + b"}", "/v1/messages"), (b'["display", "updates"]', "/v1/messages"),
(b'{"thinking": "display", "x": "updates"}', "/v1/messages"), (b'{"display": "updates"}', "/v1/messages"),
(b'{"thinking": {"display": ["updates"]}}', "/v1/messages")):
with self.subTest(raw=raw, path=path):
out, changed = self.kp.thinking_display(raw, path)
self.assertIs(out, raw)
self.assertFalse(changed)
if __name__ == "__main__":
unittest.main()