OpenJev-1.1 / helper /compat.py
abhishekgahlot's picture
OpenJev 1.1: full card, figures, helper and licence files
f2db5ff verified
Raw History Blame Contribute Delete
16 kB
"""Request-surface compatibility with the hosted Jev API, in front of the released helper. shim.py stays byte-identical and still
computes every answer but a one-level score's; a request it already accepted reaches it as the same bytes, so nothing the model sees
changes. Added here:
- GET /v1/models (the official SDKs call it; it was a 404);
- bodies sent with Content-Encoding gzip, x-gzip or zstd (the official SDKs compress by default; the helper read them as plain JSON);
- a question without `instructions` (optional on the hosted API, a 422 here) gets a neutral default;
- an array `state` is written as JSON text, the way the helper writes an object state (it wrote Python repr);
- a one-level score (the hosted API takes 1 to 10 levels, the helper 2 or more) is answered without the model: all probability on it;
- ONE image the hosted way: the `assets` map, base64 in the JSON or a multipart/form-data body (the JSON as its first part, `request`),
whose reference is the whole state or one whole top-level value of an object state, reaches the helper on today's path, `state.image`
as a data URL (the asset's key leaves the text state). Several images, images in instructions or criteria, nested or inside longer
text are a 400, and Box stays the helper's 422: the model was trained on one leading screenshot only;
- a body over 32 MiB, as sent or after decompression, is a 413;
- the answer's `model` is the requested model when the request names one (the helper's build string stays on GET /v1/version);
- every error is JSON and carries the hosted API's `detail` next to our own `error` object: malformed JSON or a malformed
compressed body β†’ 400, an unsupported Content-Encoding β†’ 415, a failure of the model server β†’ 502 (the helper closed the
connection on these).
Run exactly like shim.py, from the same folder (or with PYTHONPATH=<the helper's folder>): VLLM=http://localhost:8000/v1 python compat.py --port 8765
NOT YET CHECKED ON A GPU: the default-instruction prompt and the image mapping are shapes the model was neither trained nor measured on."""
import argparse, base64, email.message, email.parser, io, json, os, time, zlib
import shim as S
DEFAULT_INSTRUCTIONS = {"choice": "Which option is correct?", "score": "Rate the content above.", "noul": "Is the statement true?"}
RELEASE_DATE = os.environ.get("SHIM_RELEASE_DATE") or time.strftime("%Y-%m-%d") # the hosted schema requires a date; ours is unknown to the server
MAX_BODY = 32 * 1024 * 1024 # the hosted limit, for the body as sent and after decompression (docs.typesafe.ai/api/errors.md)
WINDOW_LOG_MAX = 25 # zstd frames may ask for a window of at most 32 MiB, the largest a body within MAX_BODY needs
MAX_PARTS, MAX_PART_HEADER = 2, 8192 # a multipart body is the JSON part and at most one image; each part's header block, in bytes
class ApiError(Exception):
def __init__(self, code, message):
super().__init__(message)
self.code, self.message = code, message
def zstd_reader(raw):
"""a reader over a zstd body (all frames) whose window is capped at WINDOW_LOG_MAX"""
try:
from compression import zstd # Python 3.14+
return zstd.ZstdFile(io.BytesIO(raw), options={zstd.DecompressionParameter.window_log_max: WINDOW_LOG_MAX})
except ImportError:
pass
try:
import zstandard
except ImportError:
raise ApiError(415, "this server cannot read zstd bodies (install the zstandard package or run on Python 3.14+); gzip works")
return zstandard.ZstdDecompressor(max_window_size=1 << WINDOW_LOG_MAX).stream_reader(io.BytesIO(raw), read_across_frames=True)
def gunzip(raw, limit):
"""one gzip member β†’ at most limit + 1 bytes. A second member is refused: members cost a Python loop each, and 32 MiB of empty
ones would keep the helper busy for half a minute (HTTP clients send one)"""
inflater = zlib.decompressobj(zlib.MAX_WBITS | 16) # gzip framing
data = inflater.decompress(raw, limit + 1)
if len(data) <= limit and not inflater.eof:
raise ValueError("truncated gzip stream")
if len(data) <= limit and inflater.unused_data:
raise ValueError("more than one gzip member")
return data
def inflate(raw, enc, limit=None):
"""one gzip or zstd layer β†’ at most limit + 1 bytes (limit: MAX_BODY): a bomb stops at the limit"""
limit = MAX_BODY if limit is None else limit
if enc != "zstd":
return gunzip(raw, limit)
out, n = [], 0
with zstd_reader(raw) as reader:
while n <= limit and (chunk := reader.read(min(1 << 20, limit + 1 - n))):
out.append(chunk)
n += len(chunk)
return b"".join(out)
def decode(raw, encoding):
"""the body as sent β†’ the JSON bytes; one compression layer, as the hosted API rules say"""
enc = (encoding or "identity").strip().lower()
if enc == "identity":
return raw
if enc not in ("gzip", "x-gzip", "zstd"):
raise ApiError(415, f"unsupported Content-Encoding {encoding!r}: use gzip, x-gzip or zstd, one layer")
try:
data = inflate(raw, enc)
except ApiError:
raise
except Exception as e:
raise ApiError(400, f"malformed {enc} body: {str(e)[:120]}")
if len(data) > MAX_BODY:
raise ApiError(413, "the body is over 32 MiB after decompression")
return data
def split_multipart(data, content_type):
"""multipart/form-data (RFC 7578) β†’ (the first part, `request`, as JSON bytes; {name: bytes} of the other parts). Parts are
counted and split on the boundary in linear time; only their header blocks, at most MAX_PART_HEADER bytes each, are parsed"""
delimiter = b"--" + multipart_boundary(content_type)
if data.count(delimiter) > MAX_PARTS + 1: # each part opens with the delimiter, and one more closes the body
raise ApiError(400, f"a multipart body has at most {MAX_PARTS} parts: the JSON and one image")
pieces = data.split(delimiter)[1:] # what comes before the first delimiter is a preamble
end = next((i for i, piece in enumerate(pieces) if piece.startswith(b"--")), None)
if end is None:
raise ApiError(400, "the multipart body does not end with its closing boundary")
parts = [read_part(piece) for piece in pieces[:end]]
names = [n for n, _ in parts]
if not names or names[0] != "request" or not all(names) or len(set(names)) < len(names):
raise ApiError(400, "a multipart body is the JSON as its first part, named request, then one uniquely named part per image")
return parts[0][1], dict(parts[1:])
def multipart_boundary(content_type):
"""the boundary of a multipart Content-Type: 1 to 70 characters (RFC 2046)"""
header = email.message.Message()
header["content-type"] = content_type
boundary = header.get_param("boundary")
if not isinstance(boundary, str) or not 0 < len(boundary) <= 70:
raise ApiError(400, "a multipart body needs a boundary of 1 to 70 characters in its Content-Type")
return boundary.encode("latin-1")
def read_part(piece):
"""one part as it sits between two boundaries β†’ (its form-data name, its content)"""
piece = piece.lstrip(b" \t") # transport padding after the boundary
end = piece.find(b"\r\n\r\n", 0, 2 + MAX_PART_HEADER + 4) # the blank line after the header block
if not piece.startswith(b"\r\n") or end < 0 or not piece.endswith(b"\r\n"):
raise ApiError(400, f"a multipart part is a line break, at most {MAX_PART_HEADER} bytes of headers, a blank line, its content and a line break")
headers = email.parser.BytesHeaderParser().parsebytes(piece[2:end]) # compat32: the HTTP policy raised on hostile headers
return headers.get_param("name", header="content-disposition"), piece[end + 4:-2]
def uses(v, ref):
"""how often `ref` occurs in the strings of v; object keys are not searched, as on the hosted API. Walked with a stack: the
JSON parser accepts nesting deeper than Python's recursion limit"""
count, todo = 0, [v]
while todo:
x = todo.pop()
if isinstance(x, str):
count += x.count(ref)
elif isinstance(x, dict):
todo.extend(x.values())
elif isinstance(x, list):
todo.extend(x)
return count
def one_image(body, files):
"""the `assets` map (and multipart parts) of a request β†’ its one image as state.image, or a 400 for what the model cannot read"""
assets = body.pop("assets", None)
if not isinstance(assets, dict) or len(assets) != 1:
raise ApiError(400, "this model reads exactly one image per request: `assets` needs exactly one entry")
(ref, a), = assets.items()
a = a if isinstance(a, dict) else {}
try:
raw = files.pop(a["part"]) if a.get("part") is not None else base64.b64decode(a.get("data_base64") or "", validate=True)
except (KeyError, TypeError, ValueError):
raise ApiError(400, f"asset {ref!r}: its multipart part is missing or its data_base64 is not a valid base64 string")
if files:
raise ApiError(400, f"multipart parts {sorted(files)} belong to no asset")
mime = "image/png" if raw.startswith(b"\x89PNG\r\n\x1a\n") else "image/jpeg" if raw.startswith(b"\xff\xd8\xff") else None
if not mime:
raise ApiError(400, f"asset {ref!r} is not a PNG or JPEG file")
state = body.get("state")
key = next((k for k, v in state.items() if v == ref), None) if isinstance(state, dict) else None
rest = {k: v for k, v in state.items() if k != key} if key is not None else {}
if uses(body.get("questions"), ref) or uses(state, ref) != 1 or (key is None and state != ref) or {"image", "screenshot"} & set(rest):
raise ApiError(400, "this model reads one image: its reference must be the whole state or one whole top-level value of an object "
"state (with no other image or screenshot field), used once and not in instructions or criteria")
body["state"] = {**rest, "image": f"data:{mime};base64,{base64.b64encode(raw).decode()}"}
def answer_score(state_text, q):
"""one level: all probability on it, no model call; two or more levels go to the helper's readout unchanged"""
levels = q.get("criteria")
if isinstance(levels, list) and len(levels) == 1:
return {"type": "score", "score": 0.0, "legend": {"0": levels[0]}, "probabilities": {"0": 1.0}, "confidence": 1.0}, 0
return S.answer_score(state_text, q)
S.ANSWER["score"] = answer_score # the helper dispatches through this table at call time
class H(S.H):
model = None # the request's `model`, echoed in its answer
def unauthorized(self):
return bool(S.SHIM_TOKEN) and self.headers.get("Authorization", "") != "Bearer " + S.SHIM_TOKEN
def cross_site(self):
"""a browser request from another site while no SHIM_TOKEN is set: without this a web page could make its visitor's browser
post to a helper on their machine (multipart is a CORS simple request, so no preflight stops it); SDKs never send the header"""
return not S.SHIM_TOKEN and self.headers.get("Sec-Fetch-Site", "").lower() == "cross-site"
def send_response(self, code, message=None):
self.answered = True
super().send_response(code, message)
def send_json(self, code, obj):
if code == 200 and "answers" in obj and isinstance(self.model, str):
obj = {**obj, "model": self.model}
if code >= 400 and isinstance(obj.get("error"), dict) and "detail" not in obj:
m = str(obj["error"].get("message", ""))
obj = {**obj, "detail": [{"loc": ["body"], "msg": m, "type": "value_error"}] if code == 422 else m}
super().send_json(code, obj)
def fail(self, code, message):
self.send_json(code, {"error": {"code": code, "message": message}})
def do_POST(self):
self.answered, self.model = False, None
n = int(self.headers.get("Content-Length", 0))
if n > MAX_BODY: # drained, never stored: the client gets to read the 413 and the connection stays usable
while n > 0 and (got := len(self.rfile.read(min(n, 1 << 20)))):
n -= got
return self.fail(413, "the body is over 32 MiB")
raw = self.rfile.read(n) # read before any answer: an unread body would be parsed as the next request on a kept-alive connection
if self.cross_site():
return self.fail(403, "cross-site browser requests are refused while no SHIM_TOKEN is set")
if self.unauthorized():
return self.fail(401, "missing or invalid bearer token")
try:
data = decode(raw, self.headers.get("Content-Encoding")) # 413 when it inflates past MAX_BODY, without holding more
files = {}
if self.headers.get_content_type() == "multipart/form-data":
data, files = split_multipart(data, self.headers["Content-Type"])
body = json.loads(data or b"{}")
if not isinstance(body, dict):
raise ApiError(400, "the body must be a JSON object")
changed = bool(files) or "assets" in body
if changed:
one_image(body, files)
except ApiError as e:
return self.fail(e.code, e.message)
except RecursionError:
return self.fail(400, "malformed JSON body: nested too deeply")
except ValueError as e:
return self.fail(400, f"malformed JSON body: {str(e)[:120]}")
self.model, qs = body.get("model"), body.get("questions")
for q in qs.values() if isinstance(qs, dict) else ():
if isinstance(q, dict) and q.get("instructions") is None and q.get("type") in DEFAULT_INSTRUCTIONS:
q["instructions"], changed = DEFAULT_INSTRUCTIONS[q["type"]], True
if isinstance(body.get("state"), list):
body["state"], changed = json.dumps(body["state"], ensure_ascii=False), True
if changed:
data = json.dumps(body, ensure_ascii=False).encode()
real, self.rfile = self.rfile, io.BytesIO(data) # the helper reads its body from here; untouched bytes unless something above changed
self.headers.replace_header("Content-Length", str(len(data))) if "Content-Length" in self.headers else self.headers.add_header("Content-Length", str(len(data)))
try:
super().do_POST()
except Exception as e: # the model server failed or timed out; the helper would drop the connection with no body
if self.answered:
raise
self.fail(502, f"model server error: {str(e)[:200]}")
finally:
self.rfile = real
def do_GET(self):
if self.cross_site():
return self.fail(403, "cross-site browser requests are refused while no SHIM_TOKEN is set")
if self.path.split("?")[0].rstrip("/").endswith("/v1/models"):
if self.unauthorized():
return self.fail(401, "missing or invalid bearer token")
return self.send_json(200, {"models": [{"name": S.VERSION["model_dir"], "release_date": RELEASE_DATE,
"description": "Decision model served by this machine. release_date is SHIM_RELEASE_DATE, or the day this server "
"started when it is not set; GET /v1/version gives the calibration and flags."}]})
super().do_GET()
if __name__ == "__main__":
ap = argparse.ArgumentParser(); ap.add_argument("--port", type=int, default=8765); ap.add_argument("--host", default="127.0.0.1", help="0.0.0.0 to expose (use SHIM_TOKEN)"); a = ap.parse_args()
S.letter_ids(); print(f"compat shim on :{a.port} -> {S.client.base_url}", flush=True)
S.ThreadingHTTPServer.request_queue_size = 256; S.ThreadingHTTPServer.daemon_threads = True
S.ThreadingHTTPServer((a.host, a.port), H).serve_forever()