jevblock 0.2.0__tar.gz
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-0.2.0/PKG-INFO +219 -0
- jevblock-0.2.0/README.md +192 -0
- jevblock-0.2.0/jevblock/__init__.py +36 -0
- jevblock-0.2.0/jevblock/backends.py +208 -0
- jevblock-0.2.0/jevblock/backends_anthropic.py +63 -0
- jevblock-0.2.0/jevblock/backends_ollama.py +169 -0
- jevblock-0.2.0/jevblock/backends_openai.py +86 -0
- jevblock-0.2.0/jevblock/bindings.py +50 -0
- jevblock-0.2.0/jevblock/classifier.py +254 -0
- jevblock-0.2.0/jevblock/criteria.py +189 -0
- jevblock-0.2.0/jevblock/eval.py +249 -0
- jevblock-0.2.0/jevblock/flywheel.py +141 -0
- jevblock-0.2.0/jevblock/llm.py +114 -0
- jevblock-0.2.0/jevblock/log.py +79 -0
- jevblock-0.2.0/jevblock/memblock_bridge.py +188 -0
- jevblock-0.2.0/jevblock/presets.py +188 -0
- jevblock-0.2.0/jevblock/radar.py +65 -0
- jevblock-0.2.0/jevblock/registry.py +71 -0
- jevblock-0.2.0/jevblock/replay.py +144 -0
- jevblock-0.2.0/jevblock/service.py +204 -0
- jevblock-0.2.0/jevblock/snake.py +236 -0
- jevblock-0.2.0/jevblock.egg-info/PKG-INFO +219 -0
- jevblock-0.2.0/jevblock.egg-info/SOURCES.txt +36 -0
- jevblock-0.2.0/jevblock.egg-info/dependency_links.txt +1 -0
- jevblock-0.2.0/jevblock.egg-info/entry_points.txt +5 -0
- jevblock-0.2.0/jevblock.egg-info/requires.txt +18 -0
- jevblock-0.2.0/jevblock.egg-info/top_level.txt +1 -0
- jevblock-0.2.0/pyproject.toml +43 -0
- jevblock-0.2.0/setup.cfg +4 -0
- jevblock-0.2.0/tests/test_eval.py +24 -0
- jevblock-0.2.0/tests/test_jevblock.py +124 -0
- jevblock-0.2.0/tests/test_llm_backends.py +211 -0
- jevblock-0.2.0/tests/test_log.py +23 -0
- jevblock-0.2.0/tests/test_phase3.py +52 -0
- jevblock-0.2.0/tests/test_phase4.py +60 -0
- jevblock-0.2.0/tests/test_replay.py +55 -0
- jevblock-0.2.0/tests/test_service.py +79 -0
- jevblock-0.2.0/tests/test_snake.py +67 -0
jevblock-0.2.0/PKG-INFO
ADDED
|
@@ -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.
|
jevblock-0.2.0/README.md
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
# JevBlock
|
|
2
|
+
|
|
3
|
+
**A plug-and-play decision layer for AI applications.** Describe a decision in plain language,
|
|
4
|
+
run it on whatever model you already have (a local LLM through Ollama, a small typed-decision
|
|
5
|
+
encoder, or a hosted API), get back typed answers with calibrated probabilities, and let a
|
|
6
|
+
confidence gate decide whether to act, escalate, or fall back.
|
|
7
|
+
|
|
8
|
+
JevBlock is inspired by TypeSafe's Jev "System One" model, which answers typed questions
|
|
9
|
+
(`choice`, `score`, `noul`) instead of generating text. JevBlock owns the *procedure* around
|
|
10
|
+
such a model, not the model: the block format, the gate, calibration, evaluation, a decision
|
|
11
|
+
log, and a loop that turns corrections into a fine-tuned engine. The engine is a setting.
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from jevblock import JevBlock, Question, Binding, Gate, JevBlockClassifier, OllamaBackend
|
|
15
|
+
|
|
16
|
+
block = JevBlock(
|
|
17
|
+
id="support.route",
|
|
18
|
+
purpose="Route an inbound support message.",
|
|
19
|
+
questions={
|
|
20
|
+
"team": Question("choice", "Which team should handle `message`?", {
|
|
21
|
+
"billing": "invoices, payments, refunds",
|
|
22
|
+
"technical": "bugs, outages, integrations",
|
|
23
|
+
"sales": "pricing, new purchases",
|
|
24
|
+
}),
|
|
25
|
+
"urgent": Question("noul", "Does `message` describe something blocking or time-critical?"),
|
|
26
|
+
},
|
|
27
|
+
bindings=[Binding("route", "team.choice"), Binding("urgent", "urgent.noul", threshold=(">=", 0.6, True, False))],
|
|
28
|
+
gates=[Gate("team.confidence", "<", 0.6, action="escalate")], # below this, a human or a stronger model decides
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
clf = JevBlockClassifier(OllamaBackend(model="gemma4:e2b"), [block]) # needs `ollama serve`
|
|
32
|
+
d = clf.run_block(block, {"message": "We were billed twice, please refund the duplicate today."})
|
|
33
|
+
print(d.fields) # {'route': 'billing', 'urgent': True}
|
|
34
|
+
print(d.escalate) # False
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
The same block runs unchanged on `StubBackend()` (tests), `LayaMLXBackend()` (Apple Silicon
|
|
38
|
+
encoder), `AnthropicBackend()`, `OpenAIBackend()`, or `JevHTTPBackend()`.
|
|
39
|
+
|
|
40
|
+
## Why
|
|
41
|
+
|
|
42
|
+
Software constantly needs small decisions: what does this user want, is this sensitive, which
|
|
43
|
+
team, how urgent, what should the agent do next. Today those are either brittle if-statements
|
|
44
|
+
or an LLM prompt whose output has to be parsed and whose confidence is invented. Jev showed
|
|
45
|
+
that a model can answer typed questions directly with real probabilities. JevBlock makes that
|
|
46
|
+
capability portable across engines and adds what a product needs around it:
|
|
47
|
+
|
|
48
|
+
| need | JevBlock |
|
|
49
|
+
|---|---|
|
|
50
|
+
| describe a decision once, run it anywhere | block files: questions, bindings, gates, versioned and fingerprinted |
|
|
51
|
+
| trustworthy confidence | probabilities read from the engine's own signal, temperature-calibrated per engine from your data |
|
|
52
|
+
| safe behaviour under uncertainty | gates: act, escalate, or fall back to a deterministic rule |
|
|
53
|
+
| know why a decision was made | every decision logged with its block fingerprint, probabilities and backend |
|
|
54
|
+
| get better over time | corrections and escalations become training rows; a fine-tune script produces a specialised engine |
|
|
55
|
+
| measure before trusting | one harness: accuracy, calibration error before and after fitting, latency, cost, per backend |
|
|
56
|
+
|
|
57
|
+
## What is in the repository
|
|
58
|
+
|
|
59
|
+
```text
|
|
60
|
+
jevblock/
|
|
61
|
+
criteria.py JevBlock schema, bounds (≤6 questions, ≤12 options), fingerprint, save/load
|
|
62
|
+
classifier.py run a block or a chain of blocks, shuffle-ensemble, calibration, gates, logging
|
|
63
|
+
bindings.py answers -> application fields
|
|
64
|
+
backends.py StubBackend, LayaBackend, LayaMLXBackend, LayaMLXRouterBackend, JevHTTPBackend
|
|
65
|
+
backends_ollama.py local LLMs via Ollama; confidence from token logprobs (default), votes, or a written distribution
|
|
66
|
+
backends_anthropic.py / backends_openai.py hosted LLMs, structured output (tested with mocks only)
|
|
67
|
+
llm.py shared prompt rendering and payload normalisation for generative engines
|
|
68
|
+
presets.py memory.typing, memory.noise, memory.conflict, memory.relevance, fin.query
|
|
69
|
+
eval.py the evaluation harness (python -m jevblock.eval ...)
|
|
70
|
+
flywheel.py decisions and labelled rows -> training items
|
|
71
|
+
log.py append-only decision log with corrections
|
|
72
|
+
registry.py export/list/validate blocks as JSON files (blocks/)
|
|
73
|
+
snake.py snake engine, planner, and blocks used as a real-time test bed
|
|
74
|
+
memblock_bridge.py optional integration with the MemBlock memory SDK
|
|
75
|
+
replay.py replay recorded engine answers; ablation of bindings / calibration / gate (no model)
|
|
76
|
+
service.py the decision service (jevblock-serve): HTTP endpoints for any language
|
|
77
|
+
clients/ jevblock.js and jevblock_client.py, thin clients for the service
|
|
78
|
+
scripts/ fine-tuning (RLCD, MPS/CUDA), MLX conversion, benchmarks, snake play and comparison
|
|
79
|
+
data/ synthetic labelled sets (replace with real, de-identified rows before trusting numbers)
|
|
80
|
+
benchmarks/ raw per-item results from every run in the reports
|
|
81
|
+
blocks/ the preset blocks as a registry
|
|
82
|
+
tests/ 40 tests, all runnable without models or network
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Reports, in order: `JEVBLOCK_DESIGN.md` (research and design), `PHASE2_RESULTS.md`
|
|
86
|
+
(zero-shot measurements), `PHASE3_RESULTS.md` (MemBlock integration), `PHASE4_RESULTS.md`
|
|
87
|
+
(fine-tuning loop), `PHASE5_RESULTS.md` (local LLM through Ollama), `SNAKE_HEAD_TO_HEAD.md`
|
|
88
|
+
(real-time decisions: JevBlock + local LLMs versus a typed-decision encoder, speed and accuracy).
|
|
89
|
+
|
|
90
|
+
## Install
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
pip install git+https://github.com/iexcalibur/jevblock.git # library + jevblock-serve / -eval / -replay / -registry
|
|
94
|
+
# or, for development:
|
|
95
|
+
git clone https://github.com/iexcalibur/jevblock.git && cd jevblock && pip install -e .[dev] && pytest -q
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
No runtime dependencies. Engines are optional extras (below).
|
|
99
|
+
|
|
100
|
+
## Use it from any language: the decision service
|
|
101
|
+
|
|
102
|
+
```bash
|
|
103
|
+
jevblock-serve --backend ollama:logprobs --model gemma4:e2b --log decisions.jsonl # http://127.0.0.1:8770
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
```bash
|
|
107
|
+
curl -s -X POST http://127.0.0.1:8770/decide -H 'Content-Type: application/json' \
|
|
108
|
+
-d '{"block":"fin.query","state":{"message":"I was charged twice, please refund the duplicate today"}}'
|
|
109
|
+
# → {"fields": {"route": "complaint", ...}, "escalate": false, "answers": {...probabilities...}, "decision_id": "..."}
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
Endpoints: `GET /health`, `GET /blocks`, `GET /blocks/<id>`, `POST /blocks` (register a block
|
|
113
|
+
file), `POST /decide`, `POST /correct` (record the right answer for a past decision; feeds the
|
|
114
|
+
learning loop). Ready-made clients: [`clients/jevblock.js`](clients/jevblock.js) (Node, browsers,
|
|
115
|
+
extensions) and [`clients/jevblock_client.py`](clients/jevblock_client.py). The service holds one
|
|
116
|
+
engine per backend name, serialises calls per engine, and allows cross-origin requests so a
|
|
117
|
+
browser extension can call it directly.
|
|
118
|
+
|
|
119
|
+
Engines are optional extras:
|
|
120
|
+
|
|
121
|
+
- **Ollama** (recommended local engine): install Ollama, `ollama pull gemma4:e2b`, run `ollama serve`.
|
|
122
|
+
- **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`.
|
|
123
|
+
- **Fine-tuning**: `uv pip install --python .venv/bin/python laya` (PyTorch), then `scripts/finetune_laya.py`.
|
|
124
|
+
- **Hosted APIs**: `pip install anthropic` or `pip install openai` and the provider's key in the environment.
|
|
125
|
+
|
|
126
|
+
## Measure a block on an engine
|
|
127
|
+
|
|
128
|
+
```bash
|
|
129
|
+
python -m jevblock.eval --block fin.query --backend ollama:logprobs --model gemma4:e2b \
|
|
130
|
+
--data data/fin_query.jsonl --split test --out benchmarks/results_ollama
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
Reports accuracy, expected calibration error before and after temperature fitting, accuracy
|
|
134
|
+
on the non-escalated subset, per-language accuracy, top confusions, latency and cost.
|
|
135
|
+
|
|
136
|
+
## Results so far (synthetic data, held-out rows; see the reports for caveats)
|
|
137
|
+
|
|
138
|
+
| decision | gemma4 5B via Ollama | qwen2.5 14B via Ollama | latency |
|
|
139
|
+
|---|---:|---:|---:|
|
|
140
|
+
| financial chatbot intent (8 classes) | 0.94 | 0.98 | 0.65 s / 3.8 s |
|
|
141
|
+
| is the user asking for investment advice | 0.90 | 0.98 | same call |
|
|
142
|
+
| memory block type (5 classes) | 0.75 | 0.79 | 0.87 s / 3.2 s |
|
|
143
|
+
| sensitivity category (5 classes) | 0.80 | 0.91 | same call |
|
|
144
|
+
| snake move, compact state, one question | 0.28 agreement | – | **211 ms** |
|
|
145
|
+
|
|
146
|
+
Jev's published latency is 236 to 276 ms per decision; its published accuracy on its own
|
|
147
|
+
typed-decisions benchmark is 0.727. Running that benchmark through JevBlock is the next step.
|
|
148
|
+
|
|
149
|
+
## Play snake with any engine
|
|
150
|
+
|
|
151
|
+
Visual showcase (local web UI, standard library only). Pick an engine, a state encoding and
|
|
152
|
+
the shield, then watch every decision: the probabilities over the four moves, the confidence,
|
|
153
|
+
whether the engine, the gate or the shield decided, and the latency per move.
|
|
154
|
+
|
|
155
|
+
```bash
|
|
156
|
+
ollama serve & # for the Ollama engines
|
|
157
|
+
python scripts/snake_ui.py # then open http://localhost:8765
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
Command-line runs:
|
|
161
|
+
|
|
162
|
+
```bash
|
|
163
|
+
python scripts/snake_play.py --backend ollama:logprobs --model gemma4:e2b --mode features --single-question
|
|
164
|
+
python scripts/snake_play.py --backend ollama:logprobs --model gemma4:e2b --mode features --single-question --no-shield
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
With the shield on, low-confidence and unsafe moves fall back to a deterministic planner; with
|
|
168
|
+
it off you see the engine's raw skill. `scripts/snake_compare.py` runs the full head-to-head.
|
|
169
|
+
|
|
170
|
+
## Close the loop
|
|
171
|
+
|
|
172
|
+
```bash
|
|
173
|
+
python -m jevblock.registry export blocks/ # blocks as files
|
|
174
|
+
python scripts/finetune_laya.py --model-dir <checkpoint> --out models/x \
|
|
175
|
+
--data data/memory_typing.jsonl:memory.typing --split train # RLCD fine-tune
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
Decisions logged through `DecisionLog` and corrected with `log.correct(...)` become training
|
|
179
|
+
rows via `jevblock.flywheel`; the fine-tuned checkpoint is registered as a backend and the
|
|
180
|
+
blocks do not change.
|
|
181
|
+
|
|
182
|
+
## Status
|
|
183
|
+
|
|
184
|
+
Prototype, installable from GitHub. Everything in the reports was measured on one Mac with
|
|
185
|
+
synthetic data and local models; hosted-API backends are mock-tested only. Model weights are
|
|
186
|
+
not committed. `LAYER_QUALITY.md` shows how the layer itself is measured with the model held
|
|
187
|
+
constant.
|
|
188
|
+
|
|
189
|
+
## License
|
|
190
|
+
|
|
191
|
+
Apache-2.0. Laya and Laya-MLX are by Convai Innovations and their contributors; Jev is a
|
|
192
|
+
product of TypeSafe AI. JevBlock does not include either.
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""JevBlock: plug-and-play typed classification blocks for agent memory.
|
|
2
|
+
|
|
3
|
+
A JevBlock is a small set of atomic typed questions (choice / score / noul) that a
|
|
4
|
+
System One model (Jev, Laya, Laya-MLX, or any callable) answers in one forward pass,
|
|
5
|
+
plus bindings that turn the calibrated answers into memory-block fields and actions.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
__version__ = "0.2.0"
|
|
9
|
+
|
|
10
|
+
from jevblock.criteria import JevBlock, Question, Binding, Gate, BoundsError
|
|
11
|
+
from jevblock.backends import SystemOneBackend, CallableBackend, StubBackend, LayaBackend, LayaMLXBackend, LayaMLXRouterBackend, JevHTTPBackend
|
|
12
|
+
from jevblock.classifier import JevBlockClassifier, Decision
|
|
13
|
+
from jevblock.bindings import resolve_bindings
|
|
14
|
+
from jevblock.log import DecisionLog
|
|
15
|
+
from jevblock import presets
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def AnthropicBackend(*a, **kw):
|
|
19
|
+
from jevblock.backends_anthropic import AnthropicBackend as _B
|
|
20
|
+
return _B(*a, **kw)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def OllamaBackend(*a, **kw):
|
|
24
|
+
from jevblock.backends_ollama import OllamaBackend as _B
|
|
25
|
+
return _B(*a, **kw)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def OpenAIBackend(*a, **kw):
|
|
29
|
+
from jevblock.backends_openai import OpenAIBackend as _B
|
|
30
|
+
return _B(*a, **kw)
|
|
31
|
+
|
|
32
|
+
__all__ = [
|
|
33
|
+
"JevBlock", "Question", "Binding", "Gate", "BoundsError",
|
|
34
|
+
"SystemOneBackend", "CallableBackend", "StubBackend", "LayaBackend", "LayaMLXBackend", "LayaMLXRouterBackend", "JevHTTPBackend",
|
|
35
|
+
"JevBlockClassifier", "Decision", "resolve_bindings", "presets", "AnthropicBackend", "OpenAIBackend", "OllamaBackend", "DecisionLog",
|
|
36
|
+
]
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"""System One backends. All accept (state, questions) and return the Jev/Laya answer payload:
|
|
2
|
+
|
|
3
|
+
{"answers": {qid: {"type": ..., "choice"/"score"/"noul": ..., "probabilities": {...},
|
|
4
|
+
"confidence": float}}, "usage": {...}}
|
|
5
|
+
|
|
6
|
+
Adapters: CallableBackend (any function), StubBackend (deterministic, for tests),
|
|
7
|
+
LayaBackend (PyTorch `laya`), LayaMLXBackend (Apple Silicon `laya_mlx`), JevHTTPBackend.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import hashlib
|
|
13
|
+
import math
|
|
14
|
+
import os
|
|
15
|
+
from typing import Any, Callable, Protocol
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class SystemOneBackend(Protocol):
|
|
19
|
+
name: str
|
|
20
|
+
|
|
21
|
+
def predict(self, state: Any, questions: dict[str, dict[str, Any]]) -> dict[str, Any]: ...
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class CallableBackend:
|
|
25
|
+
"""Wrap any `fn(state, questions) -> payload`."""
|
|
26
|
+
|
|
27
|
+
def __init__(self, fn: Callable[[Any, dict], dict], name: str = "callable"):
|
|
28
|
+
self._fn, self.name = fn, name
|
|
29
|
+
|
|
30
|
+
def predict(self, state, questions):
|
|
31
|
+
return self._fn(state, questions)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class StubBackend:
|
|
35
|
+
"""Deterministic keyword-driven stub so the pipeline can run and be tested without weights.
|
|
36
|
+
|
|
37
|
+
For `choice`, scores each option by keyword overlap between the option key/description and
|
|
38
|
+
the state; for `noul`, uses a small lexicon; for `score`, the position of the first matching
|
|
39
|
+
level. Confidence is normalised-entropy, identical to Laya's `confidence_from_probs`.
|
|
40
|
+
This is NOT a model; it exists so bindings, gates, chaining and the memblock bridge are testable.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
name = "stub"
|
|
44
|
+
|
|
45
|
+
NOUL_HINTS = {
|
|
46
|
+
"sensitive": ["password", "ssn", "salary", "diagnos", "card number", "api key", "token", "account number"],
|
|
47
|
+
"worth_storing": ["prefer", "works at", "lives in", "deployed", "bought", "sold", "moved", "likes", "hates", "uses"],
|
|
48
|
+
"contradicts": ["no longer", "not anymore", "actually", "instead", "sold", "moved out", "cancel"],
|
|
49
|
+
"supersedes": ["now", "changed", "new", "switched", "updated", "moved to"],
|
|
50
|
+
"is_noise": ["hello", "hi", "thanks", "ok", "bye"],
|
|
51
|
+
"answerable": ["prefer", "works", "lives", "deployed", "likes"],
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
@staticmethod
|
|
55
|
+
def _text(state) -> str:
|
|
56
|
+
if isinstance(state, str):
|
|
57
|
+
return state.lower()
|
|
58
|
+
import json
|
|
59
|
+
from jevblock.llm import public_state
|
|
60
|
+
return json.dumps(public_state(state), ensure_ascii=False, default=str).lower()
|
|
61
|
+
|
|
62
|
+
@staticmethod
|
|
63
|
+
def _softmax(z: list[float], t: float = 1.0) -> list[float]:
|
|
64
|
+
m = max(z)
|
|
65
|
+
e = [math.exp((v - m) / t) for v in z]
|
|
66
|
+
s = sum(e)
|
|
67
|
+
return [v / s for v in e]
|
|
68
|
+
|
|
69
|
+
@staticmethod
|
|
70
|
+
def _conf(p: list[float]) -> float:
|
|
71
|
+
k = len(p)
|
|
72
|
+
if k < 2:
|
|
73
|
+
return 1.0
|
|
74
|
+
ent = -sum(v * math.log(max(v, 1e-12)) for v in p)
|
|
75
|
+
return max(0.0, min(1.0, 1.0 - ent / math.log(k)))
|
|
76
|
+
|
|
77
|
+
def _seeded_noise(self, key: str) -> float:
|
|
78
|
+
h = int(hashlib.sha256(key.encode()).hexdigest()[:8], 16)
|
|
79
|
+
return (h % 1000) / 1000.0 * 0.2
|
|
80
|
+
|
|
81
|
+
def predict(self, state, questions):
|
|
82
|
+
text = self._text(state)
|
|
83
|
+
answers: dict[str, Any] = {}
|
|
84
|
+
for qid, q in questions.items():
|
|
85
|
+
t = q["type"]
|
|
86
|
+
if t == "choice":
|
|
87
|
+
crit = q["criteria"]
|
|
88
|
+
keys = list(crit.keys()) if isinstance(crit, dict) else list(crit)
|
|
89
|
+
z = []
|
|
90
|
+
for k in keys:
|
|
91
|
+
desc = (crit.get(k) if isinstance(crit, dict) else None) or ""
|
|
92
|
+
words = set((k.replace("_", " ") + " " + str(desc)).lower().replace(",", " ").split())
|
|
93
|
+
words = {w for w in words if len(w) > 3}
|
|
94
|
+
hit = sum(1 for w in words if w in text)
|
|
95
|
+
z.append(2.0 * hit + self._seeded_noise(qid + k))
|
|
96
|
+
if all(v < 1.0 for v in z):
|
|
97
|
+
# nothing matched: prefer the explicit "nothing / other" option when present
|
|
98
|
+
for j, k in enumerate(keys):
|
|
99
|
+
if k in ("ordinary", "other", "none", "NONE", "information", "approximate"):
|
|
100
|
+
z[j] += 1.5
|
|
101
|
+
p = self._softmax(z, t=0.45) # one clear keyword hit -> ~0.98, matching gate thresholds
|
|
102
|
+
i = max(range(len(p)), key=p.__getitem__)
|
|
103
|
+
answers[qid] = {"type": "choice", "choice": keys[i],
|
|
104
|
+
"probabilities": dict(zip(keys, [round(v, 4) for v in p])),
|
|
105
|
+
"confidence": round(self._conf(p), 4)}
|
|
106
|
+
elif t == "score":
|
|
107
|
+
levels = q["criteria"]
|
|
108
|
+
z = [self._seeded_noise(qid + str(i)) for i in range(len(levels))]
|
|
109
|
+
for i, lvl in enumerate(levels):
|
|
110
|
+
for w in str(lvl).lower().replace(",", " ").split():
|
|
111
|
+
if len(w) > 3 and w in text:
|
|
112
|
+
z[i] += 2.0
|
|
113
|
+
p = self._softmax(z, t=0.7)
|
|
114
|
+
exp = sum(i * v for i, v in enumerate(p))
|
|
115
|
+
answers[qid] = {"type": "score", "score": round(exp, 4),
|
|
116
|
+
"legend": {str(i): c for i, c in enumerate(levels)},
|
|
117
|
+
"probabilities": {str(i): round(v, 4) for i, v in enumerate(p)},
|
|
118
|
+
"confidence": round(self._conf(p), 4)}
|
|
119
|
+
else:
|
|
120
|
+
hints = self.NOUL_HINTS.get(qid, [])
|
|
121
|
+
hit = any(h in text for h in hints)
|
|
122
|
+
# Also honour hints embedded in the instructions (e.g. "credentials", "money back")
|
|
123
|
+
instr = q.get("instructions", "").lower()
|
|
124
|
+
p_true = 0.82 if hit else 0.18
|
|
125
|
+
if not hint_free(instr) and any(w in text for w in ("refund", "money back")) and "money" in instr:
|
|
126
|
+
p_true = 0.9
|
|
127
|
+
answers[qid] = {"type": "noul", "noul": round(p_true, 4),
|
|
128
|
+
"confidence": round(max(p_true, 1 - p_true), 4)}
|
|
129
|
+
return {"model": self.name, "answers": answers, "usage": {"input_tokens": len(text.split()), "output_tokens": 0}}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def hint_free(s: str) -> bool:
|
|
133
|
+
return not s
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class LayaBackend:
|
|
137
|
+
"""PyTorch Laya (`pip install laya`). Uses the Router so language is handled per request."""
|
|
138
|
+
|
|
139
|
+
name = "laya"
|
|
140
|
+
|
|
141
|
+
def __init__(self, preload: bool = False, device: str | None = None, **router_kw):
|
|
142
|
+
from laya import Router # type: ignore
|
|
143
|
+
self._router = Router(preload=preload, device=device, **router_kw)
|
|
144
|
+
|
|
145
|
+
def predict(self, state, questions):
|
|
146
|
+
return self._router.predict(state, questions)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
class LayaMLXBackend:
|
|
150
|
+
"""Apple Silicon Laya (`pip install laya-mlx`). 7 to 13 ms per question on M3 Max."""
|
|
151
|
+
|
|
152
|
+
name = "laya-mlx"
|
|
153
|
+
|
|
154
|
+
def __init__(self, model: str = "aac6fef/laya-mlx", dtype: str = "float16", **load_kw):
|
|
155
|
+
import laya_mlx # type: ignore
|
|
156
|
+
self._agent = laya_mlx.load(model, dtype=dtype, **load_kw)
|
|
157
|
+
|
|
158
|
+
def predict(self, state, questions):
|
|
159
|
+
from jevblock.llm import public_state
|
|
160
|
+
return self._agent.predict(public_state(state), questions)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
class LayaMLXRouterBackend:
|
|
164
|
+
"""Laya-MLX with script/language routing: English checkpoint for English, multilingual otherwise.
|
|
165
|
+
|
|
166
|
+
Phase 2 measured the English checkpoint at 0.73 / 0.85 / 0.73 (block_type / sensitivity /
|
|
167
|
+
intent) on English rows against 0.58 / 0.50 / 0.65 for the multilingual one, but 0.13 on Hindi
|
|
168
|
+
intent. Routing before the forward pass gets both.
|
|
169
|
+
"""
|
|
170
|
+
|
|
171
|
+
name = "laya-mlx-router"
|
|
172
|
+
|
|
173
|
+
def __init__(self, dtype: str = "float16", max_loaded: int = 2, **router_kw):
|
|
174
|
+
from laya_mlx import Router # type: ignore
|
|
175
|
+
self._router = Router(dtype=dtype, max_loaded=max_loaded, **router_kw)
|
|
176
|
+
|
|
177
|
+
def predict(self, state, questions):
|
|
178
|
+
from jevblock.llm import public_state
|
|
179
|
+
return self._router.predict(public_state(state), questions)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
class JevHTTPBackend:
|
|
183
|
+
"""TypeSafe Jev over HTTP. Endpoint and payload follow the public docs; adjust if they change.
|
|
184
|
+
|
|
185
|
+
Uses `TYPESAFE_API_KEY`. Never hard-code the key.
|
|
186
|
+
"""
|
|
187
|
+
|
|
188
|
+
name = "jev"
|
|
189
|
+
|
|
190
|
+
def __init__(self, api_key: str | None = None, base_url: str = "https://api.typesafe.ai/v1",
|
|
191
|
+
model: str | None = None, timeout: float = 10.0):
|
|
192
|
+
self._key = api_key or os.environ.get("TYPESAFE_API_KEY")
|
|
193
|
+
if not self._key:
|
|
194
|
+
raise RuntimeError("TYPESAFE_API_KEY is required for JevHTTPBackend")
|
|
195
|
+
self._url = base_url.rstrip("/") + "/system_one"
|
|
196
|
+
self._model = model or os.environ.get("TYPESAFE_DEFAULT_MODEL", "jev")
|
|
197
|
+
self._timeout = timeout
|
|
198
|
+
|
|
199
|
+
def predict(self, state, questions):
|
|
200
|
+
import json
|
|
201
|
+
import urllib.request
|
|
202
|
+
body = json.dumps({"model": self._model, "state": state, "questions": questions}).encode()
|
|
203
|
+
req = urllib.request.Request(
|
|
204
|
+
self._url, data=body, method="POST",
|
|
205
|
+
headers={"Content-Type": "application/json", "Authorization": f"Bearer {self._key}"},
|
|
206
|
+
)
|
|
207
|
+
with urllib.request.urlopen(req, timeout=self._timeout) as r:
|
|
208
|
+
return json.loads(r.read().decode())
|