mirror of
https://github.com/hasso5703/alzeo.git
synced 2026-12-05 12:24:28 +01:00
Claude Code reads a PDF as a document block inside the tool's result. SGLang refuses the request, the block stays in the conversation, and every turn after it was refused, /compact included (Claude Code 2.1.326 through the proxy to the request models of SGLang v0.5.21, 2026-11-30); vLLM and llama.cpp drop it and the model answers of a file it never saw. An image on a lane that reads text only did the same on SGLang and vLLM. The block a tool gave back is said to the model in words, with the way to read the file, the same words at every turn; what the person sends is the engine's to refuse on its turn, in its own words, and is said in words after it, where Claude Code keeps it in the last message. A lane that reads images gets its bodies byte for byte, and so does one the proxy does not know yet. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
237 lines
12 KiB
Python
237 lines
12 KiB
Python
"""A media the served model does not read no longer ends a Claude Code session (v6.63).
|
|
|
|
Claude Code reads a PDF as a document block inside the tool's result. SGLang refuses the request, the block
|
|
stays in the conversation, and every turn after it was refused too, /compact included (Claude Code 2.1.326
|
|
against the request models of SGLang v0.5.21, 2026-11-30). An image on a lane that reads text only did the
|
|
same. The block is said in words to the model, so that it can read the file another way."""
|
|
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"
|
|
PDF = {"type": "document", "source": {"type": "base64", "media_type": "application/pdf", "data": "JVBERi0xLjQK"}}
|
|
PNG = {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "iVBORw0KGgo="}}
|
|
|
|
|
|
def text(t):
|
|
return {"type": "text", "text": t}
|
|
|
|
|
|
def read(block, *more):
|
|
"""A conversation as Claude Code writes it once its Read tool gave a file back."""
|
|
return [{"role": "user", "content": "read x"},
|
|
{"role": "assistant", "content": [{"type": "tool_use", "id": "t1", "name": "Read", "input": {"file_path": "/x"}}]},
|
|
{"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": [text("PDF file read: /x"), block]}]},
|
|
*more]
|
|
|
|
|
|
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))
|
|
out = b'{"input_tokens": 1}'
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(out)))
|
|
self.end_headers()
|
|
self.wfile.write(out)
|
|
|
|
|
|
class Base(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_media_{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.serve("qwen3.8-27b")
|
|
|
|
def serve(self, name, engine="sglang"):
|
|
self.mod._SERVED.update(names=(name,) if name else (), engine=engine, ts=time.time())
|
|
self.mod._POOL.update(tokens=10_000_000, window=1000, ts=time.time())
|
|
|
|
def ask(self, messages, path="/v1/messages", **more):
|
|
"""(the body the proxy sent the engine, the body it was sent)"""
|
|
Engine.seen.clear()
|
|
body = json.dumps({"model": "m", "max_tokens": 5, "messages": messages, **more}).encode()
|
|
s = socket.create_connection(("127.0.0.1", self.proxy.server_address[1]), timeout=8)
|
|
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\n\r\n".encode() + body)
|
|
while s.recv(65536):
|
|
pass
|
|
finally:
|
|
s.close()
|
|
return next(raw for p, raw in Engine.seen if p == path), body
|
|
|
|
def kinds(self, raw):
|
|
"""Every block type of a body, a tool_result's own after a ">"."""
|
|
out = []
|
|
for m in json.loads(raw)["messages"]:
|
|
for b in m["content"] if isinstance(m["content"], list) else ():
|
|
out.append(b["type"])
|
|
if isinstance(b.get("content"), list):
|
|
out += [">" + x["type"] for x in b["content"]]
|
|
return out
|
|
|
|
|
|
class APdfAToolGaveBack(Base):
|
|
def test_it_is_said_to_the_model_with_the_way_to_read_it(self):
|
|
raw, _ = self.ask(read(PDF))
|
|
self.assertNotIn(">document", self.kinds(raw))
|
|
said = json.loads(raw)["messages"][2]["content"][0]["content"]
|
|
self.assertEqual(said[0], text("PDF file read: /x"))
|
|
for words in ("application/pdf", "left out", "pdftotext"):
|
|
self.assertIn(words, said[1]["text"])
|
|
self.assertNotIn(b"JVBERi0", raw)
|
|
|
|
def test_on_every_engine_and_at_every_turn_in_the_same_words(self):
|
|
turns = [read(PDF), read(PDF, {"role": "assistant", "content": [text("ok")]}, {"role": "user", "content": "hello"})]
|
|
for name, engine in (("qwen3.8-27b", "sglang"), ("nemotron-3.5-bolt", "vllm"), ("qwen3.8-flash-next-unsloth", "llamacpp")):
|
|
self.serve(name, engine)
|
|
said = [json.loads(self.ask(t)[0])["messages"][2] for t in turns]
|
|
self.assertEqual(said[0], said[1], "the prefix cache reads the same prompt again")
|
|
|
|
def test_on_the_counting_route_too(self):
|
|
raw, _ = self.ask(read(PDF), path="/v1/messages/count_tokens")
|
|
self.assertNotIn(">document", self.kinds(raw))
|
|
|
|
def test_a_document_of_text_is_its_text(self):
|
|
doc = {"type": "document", "source": {"type": "text", "media_type": "text/plain", "data": "the words"}}
|
|
raw, _ = self.ask(read(doc))
|
|
self.assertEqual(json.loads(raw)["messages"][2]["content"][0]["content"][1], text("the words"))
|
|
|
|
def test_what_its_block_carried_for_the_cache_stays(self):
|
|
raw, _ = self.ask(read({**PDF, "cache_control": {"type": "ephemeral"}}))
|
|
self.assertEqual(json.loads(raw)["messages"][2]["content"][0]["content"][1]["cache_control"], {"type": "ephemeral"})
|
|
|
|
def test_the_journal_says_it_once(self):
|
|
self.mod._unread_logged._seen.clear()
|
|
for _ in range(3):
|
|
self.ask(read(PDF))
|
|
self.assertEqual(len([ln for ln in self.journal if "does not read the document blocks" in ln]), 1, self.journal)
|
|
|
|
|
|
class AMediaThePersonSent(Base):
|
|
ASKED = [PDF, text("<system-reminder>a</system-reminder>"), text("what is in x.pdf")]
|
|
|
|
def test_in_their_last_message_it_is_the_engine_s_to_refuse(self):
|
|
raw, body = self.ask([{"role": "user", "content": self.ASKED}])
|
|
self.assertEqual(raw, body, "byte for byte")
|
|
|
|
def test_a_reminder_after_the_prompt_is_no_later_turn(self):
|
|
_ = [*self.ASKED, text(" <system-reminder>b</system-reminder>")]
|
|
raw, body = self.ask([{"role": "user", "content": _}, {"role": "system", "content": [text("# Environment")]}])
|
|
self.assertEqual(raw, body)
|
|
|
|
def test_refused_then_written_after_in_the_same_message_it_is_said(self):
|
|
"""Claude Code puts what the person writes after a refused turn in the same message (2.1.326)."""
|
|
raw, _ = self.ask([{"role": "user", "content": [*self.ASKED, text("hello")]},
|
|
{"role": "system", "content": [text("# Environment")]}])
|
|
self.assertNotIn("document", self.kinds(raw))
|
|
self.assertEqual(len(json.loads(raw)["messages"][0]["content"]), 4)
|
|
|
|
def test_in_an_older_message_it_is_said(self):
|
|
raw, _ = self.ask([{"role": "user", "content": self.ASKED}, {"role": "assistant", "content": [text("ok")]},
|
|
{"role": "user", "content": "and now"}])
|
|
self.assertNotIn("document", self.kinds(raw))
|
|
|
|
def test_before_a_tool_s_result_it_is_older(self):
|
|
raw, _ = self.ask([{"role": "user", "content": self.ASKED},
|
|
{"role": "assistant", "content": [{"type": "tool_use", "id": "t", "name": "Bash", "input": {}}]},
|
|
{"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t", "content": "done"}]}])
|
|
self.assertNotIn("document", self.kinds(raw))
|
|
|
|
|
|
class AnImage(Base):
|
|
def test_on_a_lane_that_reads_images_nothing_changes(self):
|
|
for name, engine in (("qwen3.8-27b", "sglang"), ("qwen3.8-flash-next", "sglang"), ("inkling-2-mini", "sglang"),
|
|
("qwen3.8-flash-next-fp4", "vllm"), ("ornith-1.5-122b", "vllm"), ("nemotron-3.5-super-vl", "vllm")):
|
|
self.serve(name, "sglang") # one engine: vLLM's renames are no matter here
|
|
raw, body = self.ask(read(PNG, {"role": "assistant", "content": [text("ok")]}, {"role": "user", "content": [PNG, text("x")]}))
|
|
self.assertEqual(raw, body, name)
|
|
|
|
def test_on_a_text_lane_one_a_tool_gave_back_is_said(self):
|
|
for name in sorted(self.mod.TEXT_ONLY_NAMES):
|
|
self.serve(name)
|
|
raw, _ = self.ask(read(PNG))
|
|
self.assertNotIn(">image", self.kinds(raw), name)
|
|
self.assertIn("reads text only", json.loads(raw)["messages"][2]["content"][0]["content"][1]["text"])
|
|
|
|
def test_on_a_text_lane_one_the_person_sent_follows_the_same_rule(self):
|
|
self.serve("lfm2.5-24b-a2b")
|
|
asked = [PNG, text("<system-reminder>a</system-reminder>"), text("what is in x.png")]
|
|
raw, body = self.ask([{"role": "user", "content": asked}])
|
|
self.assertEqual(raw, body)
|
|
raw, _ = self.ask([{"role": "user", "content": [*asked, text("hello")]}])
|
|
self.assertNotIn("image", self.kinds(raw))
|
|
|
|
def test_a_lane_not_known_yet_is_left_alone(self):
|
|
self.addCleanup(setattr, self.mod, "served_models", self.mod.served_models)
|
|
for served in (lambda: (), self.unreachable):
|
|
self.mod.served_models = served
|
|
raw, _ = self.mod.unread_media(json.dumps({"messages": read(PNG)}).encode(), "/v1/messages")
|
|
self.assertIn(b'"image"', raw)
|
|
|
|
def unreachable(self):
|
|
raise self.mod.EngineUnreachable("starting")
|
|
|
|
|
|
class WhatIsNotTouched(Base):
|
|
def test_a_body_with_no_such_media_goes_byte_for_byte(self):
|
|
self.serve("lfm2.5-24b-a2b")
|
|
for messages, more in (([{"role": "user", "content": "a \"document\" and an \"image\""}], {}),
|
|
([{"role": "user", "content": [text("x")]}],
|
|
{"tools": [{"name": "t", "input_schema": {"type": "object", "properties": {"document": {"type": "string"}}}}]})):
|
|
raw, body = self.ask(messages, **more)
|
|
self.assertEqual(raw, body)
|
|
|
|
def test_the_other_routes_are_not_its_business(self):
|
|
self.serve("lfm2.5-24b-a2b")
|
|
body = json.dumps({"messages": read(PDF)}).encode()
|
|
for path in ("/v1/chat/completions", "/v1/responses", "/v1/messages/batches"):
|
|
self.assertEqual(self.mod.unread_media(body, path), (body, ()))
|
|
|
|
def test_odd_shapes_are_the_engine_s(self):
|
|
for body in (b"", b"not json \"document\"", b'["document"]', b'{"messages": "document"}', b'{"messages": ["document", null]}',
|
|
b'{"messages": [{"role": "user", "content": ["document", {"type": ["document"]}]}]}'):
|
|
self.assertEqual(self.mod.unread_media(body, "/v1/messages"), (body, ()))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|