jevblock 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
jevblock/service.py ADDED
@@ -0,0 +1,204 @@
1
+ """JevBlock decision service: the layer as a local HTTP endpoint, for any language.
2
+
3
+ jevblock-serve # presets, stub engine, http://127.0.0.1:8770
4
+ jevblock-serve --backend ollama:logprobs --model gemma4:e2b --blocks blocks/ --log decisions.jsonl
5
+
6
+ Endpoints (JSON in, JSON out):
7
+
8
+ GET /health -> {"ok": true, "backend": ..., "blocks": [...]}
9
+ GET /blocks -> {id: {fingerprint, purpose, questions, observations}}
10
+ GET /blocks/<id> -> the block file
11
+ POST /blocks -> register a block file at run time (body = block JSON)
12
+ POST /decide -> {"block": "fin.query", "state": {...}, "backend": "stub"?, "ensemble": 1?}
13
+ returns fields, answers, escalate, blocked, confidence, latency, decision_id
14
+ POST /correct -> {"decision_id": "...", "labels": {"intent": "complaint"}, "by": "agent-42"}
15
+
16
+ Rules: the service holds one classifier per (backend, block) pair; engine calls are serialised
17
+ per backend (local models are single-tenant anyway); every decision is appended to the log when
18
+ one is configured, so corrections can reference it. Standard library only.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import json
25
+ import os
26
+ import threading
27
+ import time
28
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
29
+ from typing import Any
30
+ from urllib.parse import urlparse
31
+
32
+ from jevblock.classifier import JevBlockClassifier
33
+ from jevblock.criteria import BoundsError, JevBlock
34
+ from jevblock.eval import get_backend
35
+ from jevblock.log import DecisionLog
36
+ from jevblock.registry import PRESETS, load_all
37
+
38
+
39
+ class DecisionService:
40
+ def __init__(self, default_backend: str = "stub", model: str | None = None, blocks_dir: str | None = None,
41
+ log_path: str | None = None, presets: bool = True):
42
+ self.default_backend = default_backend
43
+ self.model = model
44
+ self.blocks: dict[str, JevBlock] = {}
45
+ if presets:
46
+ for bid, fn in PRESETS.items():
47
+ self.blocks[bid] = fn()
48
+ if blocks_dir and os.path.isdir(blocks_dir) and os.path.exists(os.path.join(blocks_dir, "index.json")):
49
+ self.blocks.update(load_all(blocks_dir))
50
+ self.log = DecisionLog(log_path) if log_path else None
51
+ self._backends: dict[str, Any] = {}
52
+ self._locks: dict[str, threading.Lock] = {}
53
+ self._clfs: dict[tuple[str, str, int], JevBlockClassifier] = {}
54
+ self._mu = threading.Lock()
55
+ self.started = time.time()
56
+ self.count = 0
57
+
58
+ # ------------------------------------------------------------------ engines
59
+ def backend(self, name: str | None):
60
+ name = name or self.default_backend
61
+ with self._mu:
62
+ if name not in self._backends:
63
+ self._backends[name] = get_backend(name, self.model if name == self.default_backend else None)
64
+ self._locks[name] = threading.Lock()
65
+ return name, self._backends[name], self._locks[name]
66
+
67
+ def classifier(self, backend_name: str, backend, block: JevBlock, ensemble: int) -> JevBlockClassifier:
68
+ key = (backend_name, block.fingerprint(), ensemble)
69
+ with self._mu:
70
+ if key not in self._clfs:
71
+ self._clfs[key] = JevBlockClassifier(backend, [block], ensemble=ensemble, log=self.log)
72
+ return self._clfs[key]
73
+
74
+ # ------------------------------------------------------------------ operations
75
+ def decide(self, block_id: str, state: Any, backend_name: str | None = None, ensemble: int = 1) -> dict[str, Any]:
76
+ if block_id not in self.blocks:
77
+ raise KeyError(f"unknown block {block_id!r}; loaded: {sorted(self.blocks)}")
78
+ block = self.blocks[block_id]
79
+ name, be, lock = self.backend(backend_name)
80
+ clf = self.classifier(name, be, block, max(1, int(ensemble)))
81
+ with lock: # one call at a time per engine
82
+ d = clf.run_block(block, state)
83
+ self.count += 1
84
+ return {
85
+ "decision_id": d.log_id, "block": d.fingerprint, "backend": d.backend,
86
+ "fields": d.fields, "escalate": d.escalate, "blocked": d.blocked,
87
+ "answers": {q: {k: v for k, v in a.items() if k in ("type", "choice", "score", "noul", "probabilities", "confidence")}
88
+ for q, a in d.answers.items()},
89
+ "gates_fired": d.gates_fired, "latency_ms": round(d.latency_ms, 1), "radar_ms": round(d.radar_ms, 2),
90
+ }
91
+
92
+ def correct(self, decision_id: str, labels: dict[str, Any], by: str = "client") -> dict[str, Any]:
93
+ if self.log is None:
94
+ raise RuntimeError("no decision log configured (start with --log <path>)")
95
+ if not decision_id or not isinstance(labels, dict) or not labels:
96
+ raise ValueError("decision_id and a non-empty labels dict are required")
97
+ self.log.correct(decision_id, labels, by=by)
98
+ return {"ok": True, "decision_id": decision_id, "labels": labels}
99
+
100
+ def register(self, block_json: dict[str, Any]) -> dict[str, Any]:
101
+ blk = JevBlock.from_dict(block_json)
102
+ self.blocks[blk.id] = blk
103
+ return {"ok": True, "id": blk.id, "fingerprint": blk.fingerprint()}
104
+
105
+ def describe(self) -> dict[str, Any]:
106
+ return {bid: {"fingerprint": b.fingerprint(), "purpose": b.purpose, "questions": list(b.questions),
107
+ "observations": b.observations, "version": b.version} for bid, b in self.blocks.items()}
108
+
109
+ def health(self) -> dict[str, Any]:
110
+ return {"ok": True, "backend": self.default_backend, "model": self.model, "blocks": sorted(self.blocks),
111
+ "decisions": self.count, "uptime_s": round(time.time() - self.started, 1), "log": bool(self.log)}
112
+
113
+
114
+ # ---------------------------------------------------------------------- HTTP
115
+ def make_handler(svc: DecisionService):
116
+ class Handler(BaseHTTPRequestHandler):
117
+ server_version = "jevblock/0.2"
118
+
119
+ def log_message(self, *a):
120
+ pass
121
+
122
+ def _send(self, obj, code=200):
123
+ body = json.dumps(obj, ensure_ascii=False).encode()
124
+ self.send_response(code)
125
+ self.send_header("Content-Type", "application/json; charset=utf-8")
126
+ self.send_header("Content-Length", str(len(body)))
127
+ self.send_header("Access-Control-Allow-Origin", "*")
128
+ self.send_header("Access-Control-Allow-Headers", "Content-Type")
129
+ self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
130
+ self.end_headers()
131
+ self.wfile.write(body)
132
+
133
+ def _body(self) -> dict[str, Any]:
134
+ n = int(self.headers.get("Content-Length") or 0)
135
+ return json.loads(self.rfile.read(n) or b"{}") if n else {}
136
+
137
+ def do_OPTIONS(self):
138
+ self._send({}, 204)
139
+
140
+ def do_GET(self):
141
+ p = urlparse(self.path).path.rstrip("/")
142
+ try:
143
+ if p in ("", "/health"):
144
+ return self._send(svc.health())
145
+ if p == "/blocks":
146
+ return self._send(svc.describe())
147
+ if p.startswith("/blocks/"):
148
+ bid = p[len("/blocks/"):]
149
+ if bid not in svc.blocks:
150
+ return self._send({"error": f"unknown block {bid!r}"}, 404)
151
+ return self._send(svc.blocks[bid].to_dict())
152
+ return self._send({"error": "not found"}, 404)
153
+ except Exception as e:
154
+ return self._send({"error": str(e)[:500]}, 500)
155
+
156
+ def do_POST(self):
157
+ p = urlparse(self.path).path.rstrip("/")
158
+ try:
159
+ body = self._body()
160
+ if p == "/decide":
161
+ if "block" not in body or "state" not in body:
162
+ return self._send({"error": "body needs 'block' and 'state'"}, 400)
163
+ return self._send(svc.decide(body["block"], body["state"], body.get("backend"), body.get("ensemble", 1)))
164
+ if p == "/correct":
165
+ return self._send(svc.correct(body.get("decision_id", ""), body.get("labels") or {}, body.get("by", "client")))
166
+ if p == "/blocks":
167
+ return self._send(svc.register(body), 201)
168
+ return self._send({"error": "not found"}, 404)
169
+ except KeyError as e:
170
+ return self._send({"error": str(e)}, 404)
171
+ except (ValueError, BoundsError) as e:
172
+ return self._send({"error": str(e)}, 400)
173
+ except Exception as e:
174
+ return self._send({"error": str(e)[:500]}, 500)
175
+
176
+ return Handler
177
+
178
+
179
+ def serve(svc: DecisionService, host: str = "127.0.0.1", port: int = 8770) -> ThreadingHTTPServer:
180
+ httpd = ThreadingHTTPServer((host, port), make_handler(svc))
181
+ return httpd
182
+
183
+
184
+ def main(argv=None):
185
+ ap = argparse.ArgumentParser(description="JevBlock decision service")
186
+ ap.add_argument("--host", default="127.0.0.1")
187
+ ap.add_argument("--port", type=int, default=8770)
188
+ ap.add_argument("--backend", default="stub", help="stub | ollama[:logprobs|:distribution|:vote] | laya-mlx | laya-mlx-router | anthropic | openai | jev")
189
+ ap.add_argument("--model", default=None)
190
+ ap.add_argument("--blocks", default=None, help="registry directory with index.json (see jevblock-registry export)")
191
+ ap.add_argument("--log", default=None, help="decision log path (JSONL); enables /correct")
192
+ ap.add_argument("--no-presets", action="store_true")
193
+ a = ap.parse_args(argv)
194
+ svc = DecisionService(a.backend, a.model, a.blocks, a.log, presets=not a.no_presets)
195
+ httpd = serve(svc, a.host, a.port)
196
+ print(f"jevblock decision service on http://{a.host}:{a.port} backend={a.backend} model={a.model or '-'} blocks={len(svc.blocks)} log={a.log or '-'}")
197
+ try:
198
+ httpd.serve_forever()
199
+ except KeyboardInterrupt:
200
+ pass
201
+
202
+
203
+ if __name__ == "__main__":
204
+ main()
jevblock/snake.py ADDED
@@ -0,0 +1,236 @@
1
+ """Snake as a JevBlock test bed: a System One decision every frame, no LLM in the loop.
2
+
3
+ Two prompt modes for the same block:
4
+ * "board" (default, honest): the model sees an ASCII board plus head/food coordinates and
5
+ plain direction labels. Ground truth comes from a deterministic planner.
6
+ * "hinted": the Laya-MLX demo style, where option descriptions already say which move is
7
+ safe/best. The model only has to read the labels; kept for comparison.
8
+
9
+ The planner (BFS to food, else the move that keeps the most reachable space) is both the gold
10
+ label for the harness and the safety layer behind the confidence gate when playing live.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import random
17
+ from collections import deque
18
+ from dataclasses import dataclass, field
19
+ from typing import Any
20
+
21
+ from jevblock.criteria import Binding, Gate, JevBlock, Question
22
+
23
+ DIRECTIONS = ("up", "down", "left", "right")
24
+ DELTA = {"up": (0, -1), "down": (0, 1), "left": (-1, 0), "right": (1, 0)}
25
+ OPPOSITE = {"up": "down", "down": "up", "left": "right", "right": "left"}
26
+
27
+
28
+ @dataclass
29
+ class SnakeGame:
30
+ width: int = 12
31
+ height: int = 8
32
+ seed: int = 7
33
+ body: list[tuple[int, int]] = field(default_factory=list) # head first
34
+ direction: str = "right"
35
+ food: tuple[int, int] = (0, 0)
36
+ score: int = 0
37
+ steps: int = 0
38
+ dead: bool = False
39
+
40
+ def __post_init__(self):
41
+ self._rng = random.Random(self.seed)
42
+ cx, cy = self.width // 2, self.height // 2
43
+ self.body = [(cx - i, cy) for i in range(3)]
44
+ self._spawn_food()
45
+
46
+ # ------------------------------------------------------------------ mechanics
47
+ @property
48
+ def head(self) -> tuple[int, int]:
49
+ return self.body[0]
50
+
51
+ def _spawn_food(self):
52
+ free = [(x, y) for x in range(self.width) for y in range(self.height) if (x, y) not in self.body]
53
+ self.food = self._rng.choice(free) if free else (-1, -1)
54
+
55
+ def target(self, d: str) -> tuple[int, int]:
56
+ dx, dy = DELTA[d]
57
+ return self.head[0] + dx, self.head[1] + dy
58
+
59
+ def legal(self, d: str) -> bool:
60
+ if d == OPPOSITE[self.direction] and len(self.body) > 1:
61
+ return False
62
+ x, y = self.target(d)
63
+ if not (0 <= x < self.width and 0 <= y < self.height):
64
+ return False
65
+ tail_moves = self.target(d) != self.food # tail leaves its cell unless we eat
66
+ occupied = self.body[:-1] if tail_moves else self.body
67
+ return (x, y) not in occupied
68
+
69
+ def _reachable(self, start: tuple[int, int], blocked: set[tuple[int, int]]) -> int:
70
+ seen, q = {start}, deque([start])
71
+ while q:
72
+ x, y = q.popleft()
73
+ for dx, dy in DELTA.values():
74
+ n = (x + dx, y + dy)
75
+ if 0 <= n[0] < self.width and 0 <= n[1] < self.height and n not in blocked and n not in seen:
76
+ seen.add(n); q.append(n)
77
+ return len(seen)
78
+
79
+ def _path_len(self, start: tuple[int, int], goal: tuple[int, int], blocked: set[tuple[int, int]]) -> int | None:
80
+ if start == goal:
81
+ return 0
82
+ seen, q = {start}, deque([(start, 0)])
83
+ while q:
84
+ (x, y), n = q.popleft()
85
+ for dx, dy in DELTA.values():
86
+ c = (x + dx, y + dy)
87
+ if c == goal:
88
+ return n + 1
89
+ if 0 <= c[0] < self.width and 0 <= c[1] < self.height and c not in blocked and c not in seen:
90
+ seen.add(c); q.append((c, n + 1))
91
+ return None
92
+
93
+ def analyse(self) -> dict[str, dict[str, Any]]:
94
+ """Per direction: legal, reachable space after the move, path length to food after the move."""
95
+ out = {}
96
+ for d in DIRECTIONS:
97
+ if not self.legal(d):
98
+ out[d] = {"legal": False, "space": 0, "food_path": None}
99
+ continue
100
+ t = self.target(d)
101
+ eats = t == self.food
102
+ new_body = [t] + (self.body if eats else self.body[:-1])
103
+ blocked = set(new_body[:-1]) # tail cell frees next step
104
+ space = self._reachable(t, blocked)
105
+ fp = 0 if eats else self._path_len(t, self.food, blocked)
106
+ out[d] = {"legal": True, "space": space, "food_path": fp, "eats": eats}
107
+ return out
108
+
109
+ def planner(self) -> tuple[str, list[str]]:
110
+ """(best move, safe moves). Safe = legal and keeps at least len(body) reachable cells."""
111
+ info = self.analyse()
112
+ safe = [d for d in DIRECTIONS if info[d]["legal"] and info[d]["space"] >= len(self.body)]
113
+ cands = safe or [d for d in DIRECTIONS if info[d]["legal"]]
114
+ if not cands:
115
+ return self.direction, []
116
+ with_food = [d for d in cands if info[d]["food_path"] is not None]
117
+ if with_food:
118
+ best = min(with_food, key=lambda d: (info[d]["food_path"], -info[d]["space"]))
119
+ else:
120
+ best = max(cands, key=lambda d: info[d]["space"])
121
+ return best, safe
122
+
123
+ def step(self, d: str) -> bool:
124
+ """Apply a move. Returns False if the snake died."""
125
+ self.steps += 1
126
+ if not self.legal(d):
127
+ self.dead = True
128
+ return False
129
+ t = self.target(d)
130
+ self.direction = d
131
+ if t == self.food:
132
+ self.body.insert(0, t); self.score += 1; self._spawn_food()
133
+ else:
134
+ self.body.insert(0, t); self.body.pop()
135
+ return True
136
+
137
+ # ------------------------------------------------------------------ prompts
138
+ def board_text(self) -> str:
139
+ rows = []
140
+ for y in range(self.height):
141
+ row = ""
142
+ for x in range(self.width):
143
+ c = (x, y)
144
+ row += "H" if c == self.head else "o" if c in self.body else "F" if c == self.food else "."
145
+ rows.append(row)
146
+ return "\n".join(rows)
147
+
148
+ def state(self, mode: str = "board") -> dict[str, Any]:
149
+ hx, hy = self.head
150
+ fx, fy = self.food
151
+ if mode == "board":
152
+ return {
153
+ "board": self.board_text(),
154
+ "legend": "H head, o body, F food, . empty; x grows right, y grows down",
155
+ "head": [hx, hy], "food": [fx, fy], "heading": self.direction, "length": len(self.body),
156
+ "food_direction": f"{'up' if fy < hy else 'down' if fy > hy else 'same row'}, "
157
+ f"{'left' if fx < hx else 'right' if fx > hx else 'same column'}",
158
+ }
159
+ if mode in ("features", "radar"):
160
+ # Compact, honest encoding (~60 tokens): what a player can see, nothing the planner decided.
161
+ legal = {d: self.legal(d) for d in DIRECTIONS}
162
+ st = {"heading": self.direction, "length": len(self.body),
163
+ "food": f"{abs(fy - hy)} {'up' if fy < hy else 'down'}, {abs(fx - hx)} {'left' if fx < hx else 'right'}",
164
+ "blocked": [d for d in DIRECTIONS if not legal[d]] or ["none"]}
165
+ if mode == "radar":
166
+ st["_game"] = self # consumed by the snake.lookahead radar, never sent to the engine
167
+ return st
168
+ # hinted: the Laya-MLX demo style, answer leaks into the labels
169
+ best, safe = self.planner()
170
+ info = self.analyse()
171
+ return {"safe_route": "yes" if safe else "no",
172
+ "hints": {d: ("Blocked. Collision." if not info[d]["legal"] else "Unsafe. Traps the snake." if d not in safe
173
+ else "Safe. Eat food now. Best." if info[d].get("eats") else "Safe. Best route to food." if d == best
174
+ else "Safe. Slower route.") for d in DIRECTIONS}}
175
+
176
+
177
+ def snake_move_block(mode: str = "board", single_question: bool = False) -> JevBlock:
178
+ """`single_question=True` drops the `trapped` noul so an LLM backend makes one call per frame."""
179
+ if mode == "features":
180
+ crit = {d: None for d in DIRECTIONS}
181
+ instr = ("Choose the snake's next move. `blocked` lists directions that hit a wall, the body, or reverse "
182
+ "`heading` (fatal). `food` says where the food is relative to the head. Move toward the food "
183
+ "without choosing a blocked direction.")
184
+ elif mode == "radar":
185
+ crit = {d: None for d in DIRECTIONS}
186
+ instr = ("Choose the snake's next move. `lookahead` reports, for each direction, how many free cells "
187
+ "remain reachable after that move and how far the food is. Avoid blocked directions, avoid "
188
+ "moves that leave few free cells (the snake gets trapped), and prefer moves that reach the food sooner.")
189
+ elif mode == "board":
190
+ crit = {"up": "move the head one cell up (y - 1)", "down": "move the head one cell down (y + 1)",
191
+ "left": "move the head one cell left (x - 1)", "right": "move the head one cell right (x + 1)"}
192
+ instr = ("Choose the next move for the snake shown in `board`. A move is fatal if it hits a wall or the "
193
+ "body, or reverses the current `heading`. Prefer the move that gets closer to the food without "
194
+ "getting trapped.")
195
+ else:
196
+ crit = {d: None for d in DIRECTIONS}
197
+ instr = "Choose the best safe move toward food using `hints`."
198
+ questions = {"move": Question("choice", instr, crit)}
199
+ bindings = [Binding("move", "move.choice"), Binding("move_confidence", "move.confidence")]
200
+ if not single_question:
201
+ questions["trapped"] = Question("noul", "Is the snake about to be trapped with no safe route forward?")
202
+ bindings.append(Binding("trapped", "trapped.noul", threshold=(">=", 0.6, True, False)))
203
+ return JevBlock(
204
+ id=f"snake.move_{mode}" + ("_1q" if single_question else ""),
205
+ purpose="One typed decision per frame: which way should the snake move?",
206
+ state_fields={"board": ["board", "head", "food", "heading"], "hinted": ["safe_route", "hints"],
207
+ "features": ["heading", "food", "blocked"], "radar": ["heading", "food", "blocked", "lookahead"]}[mode],
208
+ questions=questions,
209
+ bindings=bindings,
210
+ observations=["snake.lookahead"] if mode == "radar" else [],
211
+ gates=[Gate("move.confidence", "<", 0.45, action="escalate")], # escalate = hand the move to the planner
212
+ )
213
+
214
+
215
+ def record_states(n: int = 300, seed: int = 11, width: int = 12, height: int = 8, epsilon: float = 0.15) -> list[dict[str, Any]]:
216
+ """Play with the planner (plus epsilon-random safe moves for variety) and record labelled states."""
217
+ rng = random.Random(seed)
218
+ rows, game = [], SnakeGame(width, height, seed=seed)
219
+ while len(rows) < n:
220
+ best, safe = game.planner()
221
+ rows.append({"state": game.state("board"), "state_hinted": game.state("hinted"),
222
+ "gold": {"move": best, "trapped": "true" if not safe else "false"},
223
+ "safe": safe, "lang": "en"})
224
+ move = rng.choice(safe) if safe and rng.random() < epsilon else best
225
+ if not game.step(move) or game.steps > 2000:
226
+ game = SnakeGame(width, height, seed=rng.randrange(10_000))
227
+ return rows
228
+
229
+
230
+ def write_dataset(path: str, n: int = 300) -> int:
231
+ rows = record_states(n)
232
+ with open(path, "w", encoding="utf-8") as f:
233
+ for i, r in enumerate(rows):
234
+ r["id"] = f"snake-{i:04d}"
235
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
236
+ return len(rows)
@@ -0,0 +1,219 @@
1
+ Metadata-Version: 2.4
2
+ Name: jevblock
3
+ Version: 0.2.0
4
+ Summary: Plug-and-play decision layer: typed decisions (choice/score/noul) with calibrated confidence, gates and a learning loop, on any model.
5
+ Author: iexcalibur
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/iexcalibur/jevblock
8
+ Keywords: classification,decision,llm,ollama,calibration,typed-decisions
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
13
+ Requires-Python: >=3.10
14
+ Description-Content-Type: text/markdown
15
+ Provides-Extra: laya
16
+ Requires-Dist: laya; extra == "laya"
17
+ Provides-Extra: mlx
18
+ Requires-Dist: laya-mlx; extra == "mlx"
19
+ Provides-Extra: memblock
20
+ Requires-Dist: memblock; extra == "memblock"
21
+ Provides-Extra: anthropic
22
+ Requires-Dist: anthropic; extra == "anthropic"
23
+ Provides-Extra: openai
24
+ Requires-Dist: openai; extra == "openai"
25
+ Provides-Extra: dev
26
+ Requires-Dist: pytest; extra == "dev"
27
+
28
+ # JevBlock
29
+
30
+ **A plug-and-play decision layer for AI applications.** Describe a decision in plain language,
31
+ run it on whatever model you already have (a local LLM through Ollama, a small typed-decision
32
+ encoder, or a hosted API), get back typed answers with calibrated probabilities, and let a
33
+ confidence gate decide whether to act, escalate, or fall back.
34
+
35
+ JevBlock is inspired by TypeSafe's Jev "System One" model, which answers typed questions
36
+ (`choice`, `score`, `noul`) instead of generating text. JevBlock owns the *procedure* around
37
+ such a model, not the model: the block format, the gate, calibration, evaluation, a decision
38
+ log, and a loop that turns corrections into a fine-tuned engine. The engine is a setting.
39
+
40
+ ```python
41
+ from jevblock import JevBlock, Question, Binding, Gate, JevBlockClassifier, OllamaBackend
42
+
43
+ block = JevBlock(
44
+ id="support.route",
45
+ purpose="Route an inbound support message.",
46
+ questions={
47
+ "team": Question("choice", "Which team should handle `message`?", {
48
+ "billing": "invoices, payments, refunds",
49
+ "technical": "bugs, outages, integrations",
50
+ "sales": "pricing, new purchases",
51
+ }),
52
+ "urgent": Question("noul", "Does `message` describe something blocking or time-critical?"),
53
+ },
54
+ bindings=[Binding("route", "team.choice"), Binding("urgent", "urgent.noul", threshold=(">=", 0.6, True, False))],
55
+ gates=[Gate("team.confidence", "<", 0.6, action="escalate")], # below this, a human or a stronger model decides
56
+ )
57
+
58
+ clf = JevBlockClassifier(OllamaBackend(model="gemma4:e2b"), [block]) # needs `ollama serve`
59
+ d = clf.run_block(block, {"message": "We were billed twice, please refund the duplicate today."})
60
+ print(d.fields) # {'route': 'billing', 'urgent': True}
61
+ print(d.escalate) # False
62
+ ```
63
+
64
+ The same block runs unchanged on `StubBackend()` (tests), `LayaMLXBackend()` (Apple Silicon
65
+ encoder), `AnthropicBackend()`, `OpenAIBackend()`, or `JevHTTPBackend()`.
66
+
67
+ ## Why
68
+
69
+ Software constantly needs small decisions: what does this user want, is this sensitive, which
70
+ team, how urgent, what should the agent do next. Today those are either brittle if-statements
71
+ or an LLM prompt whose output has to be parsed and whose confidence is invented. Jev showed
72
+ that a model can answer typed questions directly with real probabilities. JevBlock makes that
73
+ capability portable across engines and adds what a product needs around it:
74
+
75
+ | need | JevBlock |
76
+ |---|---|
77
+ | describe a decision once, run it anywhere | block files: questions, bindings, gates, versioned and fingerprinted |
78
+ | trustworthy confidence | probabilities read from the engine's own signal, temperature-calibrated per engine from your data |
79
+ | safe behaviour under uncertainty | gates: act, escalate, or fall back to a deterministic rule |
80
+ | know why a decision was made | every decision logged with its block fingerprint, probabilities and backend |
81
+ | get better over time | corrections and escalations become training rows; a fine-tune script produces a specialised engine |
82
+ | measure before trusting | one harness: accuracy, calibration error before and after fitting, latency, cost, per backend |
83
+
84
+ ## What is in the repository
85
+
86
+ ```text
87
+ jevblock/
88
+ criteria.py JevBlock schema, bounds (≤6 questions, ≤12 options), fingerprint, save/load
89
+ classifier.py run a block or a chain of blocks, shuffle-ensemble, calibration, gates, logging
90
+ bindings.py answers -> application fields
91
+ backends.py StubBackend, LayaBackend, LayaMLXBackend, LayaMLXRouterBackend, JevHTTPBackend
92
+ backends_ollama.py local LLMs via Ollama; confidence from token logprobs (default), votes, or a written distribution
93
+ backends_anthropic.py / backends_openai.py hosted LLMs, structured output (tested with mocks only)
94
+ llm.py shared prompt rendering and payload normalisation for generative engines
95
+ presets.py memory.typing, memory.noise, memory.conflict, memory.relevance, fin.query
96
+ eval.py the evaluation harness (python -m jevblock.eval ...)
97
+ flywheel.py decisions and labelled rows -> training items
98
+ log.py append-only decision log with corrections
99
+ registry.py export/list/validate blocks as JSON files (blocks/)
100
+ snake.py snake engine, planner, and blocks used as a real-time test bed
101
+ memblock_bridge.py optional integration with the MemBlock memory SDK
102
+ replay.py replay recorded engine answers; ablation of bindings / calibration / gate (no model)
103
+ service.py the decision service (jevblock-serve): HTTP endpoints for any language
104
+ clients/ jevblock.js and jevblock_client.py, thin clients for the service
105
+ scripts/ fine-tuning (RLCD, MPS/CUDA), MLX conversion, benchmarks, snake play and comparison
106
+ data/ synthetic labelled sets (replace with real, de-identified rows before trusting numbers)
107
+ benchmarks/ raw per-item results from every run in the reports
108
+ blocks/ the preset blocks as a registry
109
+ tests/ 40 tests, all runnable without models or network
110
+ ```
111
+
112
+ Reports, in order: `JEVBLOCK_DESIGN.md` (research and design), `PHASE2_RESULTS.md`
113
+ (zero-shot measurements), `PHASE3_RESULTS.md` (MemBlock integration), `PHASE4_RESULTS.md`
114
+ (fine-tuning loop), `PHASE5_RESULTS.md` (local LLM through Ollama), `SNAKE_HEAD_TO_HEAD.md`
115
+ (real-time decisions: JevBlock + local LLMs versus a typed-decision encoder, speed and accuracy).
116
+
117
+ ## Install
118
+
119
+ ```bash
120
+ pip install git+https://github.com/iexcalibur/jevblock.git # library + jevblock-serve / -eval / -replay / -registry
121
+ # or, for development:
122
+ git clone https://github.com/iexcalibur/jevblock.git && cd jevblock && pip install -e .[dev] && pytest -q
123
+ ```
124
+
125
+ No runtime dependencies. Engines are optional extras (below).
126
+
127
+ ## Use it from any language: the decision service
128
+
129
+ ```bash
130
+ jevblock-serve --backend ollama:logprobs --model gemma4:e2b --log decisions.jsonl # http://127.0.0.1:8770
131
+ ```
132
+
133
+ ```bash
134
+ curl -s -X POST http://127.0.0.1:8770/decide -H 'Content-Type: application/json' \
135
+ -d '{"block":"fin.query","state":{"message":"I was charged twice, please refund the duplicate today"}}'
136
+ # → {"fields": {"route": "complaint", ...}, "escalate": false, "answers": {...probabilities...}, "decision_id": "..."}
137
+ ```
138
+
139
+ Endpoints: `GET /health`, `GET /blocks`, `GET /blocks/<id>`, `POST /blocks` (register a block
140
+ file), `POST /decide`, `POST /correct` (record the right answer for a past decision; feeds the
141
+ learning loop). Ready-made clients: [`clients/jevblock.js`](clients/jevblock.js) (Node, browsers,
142
+ extensions) and [`clients/jevblock_client.py`](clients/jevblock_client.py). The service holds one
143
+ engine per backend name, serialises calls per engine, and allows cross-origin requests so a
144
+ browser extension can call it directly.
145
+
146
+ Engines are optional extras:
147
+
148
+ - **Ollama** (recommended local engine): install Ollama, `ollama pull gemma4:e2b`, run `ollama serve`.
149
+ - **Laya-MLX** (Apple Silicon encoder): needs an arm64 Python; `uv venv --python 3.12 --python-preference only-managed .venv && uv pip install --python .venv/bin/python laya-mlx`.
150
+ - **Fine-tuning**: `uv pip install --python .venv/bin/python laya` (PyTorch), then `scripts/finetune_laya.py`.
151
+ - **Hosted APIs**: `pip install anthropic` or `pip install openai` and the provider's key in the environment.
152
+
153
+ ## Measure a block on an engine
154
+
155
+ ```bash
156
+ python -m jevblock.eval --block fin.query --backend ollama:logprobs --model gemma4:e2b \
157
+ --data data/fin_query.jsonl --split test --out benchmarks/results_ollama
158
+ ```
159
+
160
+ Reports accuracy, expected calibration error before and after temperature fitting, accuracy
161
+ on the non-escalated subset, per-language accuracy, top confusions, latency and cost.
162
+
163
+ ## Results so far (synthetic data, held-out rows; see the reports for caveats)
164
+
165
+ | decision | gemma4 5B via Ollama | qwen2.5 14B via Ollama | latency |
166
+ |---|---:|---:|---:|
167
+ | financial chatbot intent (8 classes) | 0.94 | 0.98 | 0.65 s / 3.8 s |
168
+ | is the user asking for investment advice | 0.90 | 0.98 | same call |
169
+ | memory block type (5 classes) | 0.75 | 0.79 | 0.87 s / 3.2 s |
170
+ | sensitivity category (5 classes) | 0.80 | 0.91 | same call |
171
+ | snake move, compact state, one question | 0.28 agreement | – | **211 ms** |
172
+
173
+ Jev's published latency is 236 to 276 ms per decision; its published accuracy on its own
174
+ typed-decisions benchmark is 0.727. Running that benchmark through JevBlock is the next step.
175
+
176
+ ## Play snake with any engine
177
+
178
+ Visual showcase (local web UI, standard library only). Pick an engine, a state encoding and
179
+ the shield, then watch every decision: the probabilities over the four moves, the confidence,
180
+ whether the engine, the gate or the shield decided, and the latency per move.
181
+
182
+ ```bash
183
+ ollama serve & # for the Ollama engines
184
+ python scripts/snake_ui.py # then open http://localhost:8765
185
+ ```
186
+
187
+ Command-line runs:
188
+
189
+ ```bash
190
+ python scripts/snake_play.py --backend ollama:logprobs --model gemma4:e2b --mode features --single-question
191
+ python scripts/snake_play.py --backend ollama:logprobs --model gemma4:e2b --mode features --single-question --no-shield
192
+ ```
193
+
194
+ With the shield on, low-confidence and unsafe moves fall back to a deterministic planner; with
195
+ it off you see the engine's raw skill. `scripts/snake_compare.py` runs the full head-to-head.
196
+
197
+ ## Close the loop
198
+
199
+ ```bash
200
+ python -m jevblock.registry export blocks/ # blocks as files
201
+ python scripts/finetune_laya.py --model-dir <checkpoint> --out models/x \
202
+ --data data/memory_typing.jsonl:memory.typing --split train # RLCD fine-tune
203
+ ```
204
+
205
+ Decisions logged through `DecisionLog` and corrected with `log.correct(...)` become training
206
+ rows via `jevblock.flywheel`; the fine-tuned checkpoint is registered as a backend and the
207
+ blocks do not change.
208
+
209
+ ## Status
210
+
211
+ Prototype, installable from GitHub. Everything in the reports was measured on one Mac with
212
+ synthetic data and local models; hosted-API backends are mock-tested only. Model weights are
213
+ not committed. `LAYER_QUALITY.md` shows how the layer itself is measured with the model held
214
+ constant.
215
+
216
+ ## License
217
+
218
+ Apache-2.0. Laya and Laya-MLX are by Convai Innovations and their contributors; Jev is a
219
+ product of TypeSafe AI. JevBlock does not include either.