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/eval.py ADDED
@@ -0,0 +1,249 @@
1
+ """Phase 2 evaluation harness: one block, one backend, one labelled JSONL, one report.
2
+
3
+ Metrics per gold question:
4
+ accuracy, ECE (15 bins, confidence = top probability), NLL,
5
+ ECE / accuracy after fitting temperatures on the train split and applying them to the test split,
6
+ gate escalation rate and accuracy on the non-escalated ("automated") subset.
7
+ Plus latency p50 / p95 and estimated cost per 1,000 decisions from reported token usage.
8
+
9
+ Usage:
10
+ python -m jevblock.eval --block memory.typing --backend stub --data data/memory_typing.jsonl
11
+ python -m jevblock.eval --block fin.query --backend laya-mlx --data data/fin_query.jsonl --out benchmarks/results
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import json
18
+ import math
19
+ import os
20
+ import statistics
21
+ import time
22
+ from typing import Any
23
+
24
+ from jevblock import presets
25
+ from jevblock.classifier import JevBlockClassifier, _recalibrate, _temp_bucket
26
+ from jevblock.criteria import JevBlock
27
+
28
+ # USD per 1M tokens (input, output). Laya/stub are local: 0.
29
+ PRICES = {"anthropic:claude-opus-5": (5.0, 25.0), "anthropic:claude-sonnet-5": (2.0, 10.0),
30
+ "anthropic:claude-haiku-4-5": (1.0, 5.0), "openai:gpt-5": (1.25, 10.0), "jev": (0.042, 0.0)}
31
+
32
+
33
+ # --------------------------------------------------------------------------- helpers
34
+ def load_jsonl(path: str) -> list[dict[str, Any]]:
35
+ with open(path, encoding="utf-8") as f:
36
+ return [json.loads(line) for line in f if line.strip()]
37
+
38
+
39
+ def get_block(name: str) -> JevBlock:
40
+ from jevblock.snake import snake_move_block
41
+ table = {"memory.typing": presets.memory_typing, "memory.noise": presets.memory_noise,
42
+ "memory.conflict": presets.memory_conflict, "fin.query": presets.fin_query,
43
+ "memory.relevance": presets.memory_relevance,
44
+ "snake.move_board": lambda: snake_move_block("board"), "snake.move_hinted": lambda: snake_move_block("hinted")}
45
+ if name not in table:
46
+ raise SystemExit(f"unknown block {name!r}; one of {sorted(table)}")
47
+ return table[name]()
48
+
49
+
50
+ def get_backend(name: str, model: str | None = None):
51
+ if name == "stub":
52
+ from jevblock.backends import StubBackend
53
+ return StubBackend()
54
+ if name == "laya-mlx":
55
+ from jevblock.backends import LayaMLXBackend
56
+ return LayaMLXBackend(model or "aac6fef/laya-multilingual-mlx")
57
+ if name == "laya-mlx-router":
58
+ from jevblock.backends import LayaMLXRouterBackend
59
+ return LayaMLXRouterBackend()
60
+ if name == "laya":
61
+ from jevblock.backends import LayaBackend
62
+ return LayaBackend(preload=True)
63
+ if name == "anthropic":
64
+ from jevblock.backends_anthropic import AnthropicBackend
65
+ return AnthropicBackend(model=model or "claude-opus-5")
66
+ if name == "openai":
67
+ from jevblock.backends_openai import OpenAIBackend
68
+ return OpenAIBackend(model=model or "gpt-5")
69
+ if name.startswith("ollama"):
70
+ from jevblock.backends_ollama import OllamaBackend
71
+ mode = name.split(":", 1)[1] if ":" in name else "logprobs" # ollama | ollama:distribution | ollama:logprobs | ollama:vote
72
+ return OllamaBackend(model=model or "gemma4:e2b", mode=mode)
73
+ if name == "jev":
74
+ from jevblock.backends import JevHTTPBackend
75
+ return JevHTTPBackend()
76
+ raise SystemExit(f"unknown backend {name!r}")
77
+
78
+
79
+ def _probs(a: dict[str, Any]) -> dict[str, float]:
80
+ return a.get("probabilities") or {"false": 1 - a["noul"], "true": a["noul"]}
81
+
82
+
83
+ def _pred(a: dict[str, Any]) -> str:
84
+ p = _probs(a)
85
+ return max(p, key=p.get)
86
+
87
+
88
+ def ece(confs: list[float], correct: list[float], bins: int = 15) -> float:
89
+ if not confs:
90
+ return float("nan")
91
+ e = 0.0
92
+ n = len(confs)
93
+ for b in range(bins):
94
+ lo, hi = b / bins, (b + 1) / bins
95
+ idx = [i for i, c in enumerate(confs) if (lo < c <= hi) or (b == 0 and c == 0)]
96
+ if idx:
97
+ e += len(idx) / n * abs(sum(confs[i] for i in idx) / len(idx) - sum(correct[i] for i in idx) / len(idx))
98
+ return e
99
+
100
+
101
+ def _metrics(rows: list[tuple[dict[str, Any], str]]) -> dict[str, float]:
102
+ """rows: [(answer, gold)]"""
103
+ if not rows:
104
+ return {"n": 0}
105
+ confs, corr, nll = [], [], []
106
+ for a, gold in rows:
107
+ p = _probs(a)
108
+ confs.append(max(p.values()))
109
+ corr.append(1.0 if _pred(a) == gold else 0.0)
110
+ nll.append(-math.log(max(p.get(gold, 0.0), 1e-9)))
111
+ return {"n": len(rows), "accuracy": round(sum(corr) / len(corr), 4), "ece": round(ece(confs, corr), 4),
112
+ "nll": round(sum(nll) / len(nll), 4), "mean_conf": round(sum(confs) / len(confs), 4)}
113
+
114
+
115
+ # --------------------------------------------------------------------------- run
116
+ def evaluate(block: JevBlock, backend, data: list[dict[str, Any]], *, ensemble: int = 1,
117
+ limit: int | None = None, verbose: bool = False, split: str | None = None) -> dict[str, Any]:
118
+ """`split`: None = all rows (train = even, test = odd, for temperature fitting);
119
+ "test" = evaluate only the odd rows, which is what a checkpoint fine-tuned on the even
120
+ rows must be scored on. Calibration is then fitted/evaluated on alternating test rows."""
121
+ if split == "test":
122
+ data = [r for i, r in enumerate(data) if i % 2 == 1]
123
+ elif split == "train":
124
+ data = [r for i, r in enumerate(data) if i % 2 == 0]
125
+ if limit:
126
+ data = data[:limit]
127
+ clf = JevBlockClassifier(backend, [block], ensemble=ensemble)
128
+ qids = [q for q in block.questions if any(q in r["gold"] for r in data)]
129
+ per_item: list[dict[str, Any]] = []
130
+ latencies, in_tok, out_tok = [], 0, 0
131
+ t_all = time.perf_counter()
132
+ for i, r in enumerate(data):
133
+ t0 = time.perf_counter()
134
+ state = r.get("state_hinted", r["state"]) if block.id.endswith("_hinted") else r["state"]
135
+ d = clf.run_block(block, state)
136
+ latencies.append((time.perf_counter() - t0) * 1000)
137
+ # usage is only available from the raw backend call; re-query cheaply via last predict if exposed
138
+ per_item.append({"id": r.get("id", i), "lang": r.get("lang", "?"), "gold": r["gold"], "answers": d.answers,
139
+ "escalate": d.escalate, "blocked": d.blocked, "fields": d.fields, "split": "train" if i % 2 == 0 else "test"})
140
+ if verbose and i % 25 == 0:
141
+ print(f" {i}/{len(data)}", flush=True)
142
+ wall = time.perf_counter() - t_all
143
+
144
+ # token usage: ask the backend directly for one representative call so cost is estimable
145
+ usage = backend.predict(data[0].get("state_hinted", data[0]["state"]) if block.id.endswith("_hinted") else data[0]["state"],
146
+ block.to_laya_questions()).get("usage", {})
147
+ in_tok, out_tok = usage.get("input_tokens", 0), usage.get("output_tokens", 0)
148
+ price_in, price_out = PRICES.get(getattr(backend, "name", ""), (0.0, 0.0))
149
+ cost_per_1k = (in_tok * price_in + out_tok * price_out) / 1e6 * 1000
150
+
151
+ report: dict[str, Any] = {
152
+ "block": block.fingerprint(), "backend": getattr(backend, "name", "?"), "n": len(data), "ensemble": ensemble,
153
+ "latency_ms": {"p50": round(statistics.median(latencies), 1),
154
+ "p95": round(sorted(latencies)[int(0.95 * (len(latencies) - 1))], 1),
155
+ "mean": round(sum(latencies) / len(latencies), 1), "wall_s": round(wall, 1)},
156
+ "tokens_per_call": {"input": in_tok, "output": out_tok}, "cost_usd_per_1k_decisions": round(cost_per_1k, 4),
157
+ "escalation_rate": round(sum(1 for p in per_item if p["escalate"]) / len(per_item), 4),
158
+ "questions": {},
159
+ }
160
+
161
+ for qid in qids:
162
+ rows = [(p["answers"][qid], str(p["gold"][qid])) for p in per_item if qid in p["gold"]]
163
+ train = [(p["answers"][qid], str(p["gold"][qid])) for p in per_item if qid in p["gold"] and p["split"] == "train"]
164
+ test = [(p["answers"][qid], str(p["gold"][qid])) for p in per_item if qid in p["gold"] and p["split"] == "test"]
165
+ auto = [(p["answers"][qid], str(p["gold"][qid])) for p in per_item if qid in p["gold"] and not p["escalate"]]
166
+ temps = JevBlockClassifier.fit_temperatures(train)
167
+ recal = []
168
+ for a, g in test:
169
+ k = len(_probs(a))
170
+ t = temps.get(_temp_bucket(a["type"], k))
171
+ recal.append((_recalibrate(a, t) if t else a, g))
172
+ by_lang = {}
173
+ for lang in sorted({p["lang"] for p in per_item}):
174
+ sub = [(p["answers"][qid], str(p["gold"][qid])) for p in per_item if qid in p["gold"] and p["lang"] == lang]
175
+ if sub:
176
+ by_lang[lang] = _metrics(sub)
177
+ # confusion (top 6 errors)
178
+ conf: dict[str, int] = {}
179
+ for a, g in rows:
180
+ pr = _pred(a)
181
+ if pr != g:
182
+ conf[f"{g}->{pr}"] = conf.get(f"{g}->{pr}", 0) + 1
183
+ report["questions"][qid] = {
184
+ "all": _metrics(rows),
185
+ "test_raw": _metrics(test),
186
+ "test_recalibrated": _metrics(recal),
187
+ "fitted_temperatures": temps,
188
+ "automated_subset": _metrics(auto),
189
+ "by_lang": by_lang,
190
+ "top_errors": dict(sorted(conf.items(), key=lambda kv: -kv[1])[:6]),
191
+ }
192
+ report["_items"] = per_item
193
+ return report
194
+
195
+
196
+ # --------------------------------------------------------------------------- report
197
+ def to_markdown(rep: dict[str, Any]) -> str:
198
+ L = [f"### {rep['block']} on `{rep['backend']}` (n={rep['n']}, ensemble={rep['ensemble']})", "",
199
+ f"latency p50 {rep['latency_ms']['p50']} ms, p95 {rep['latency_ms']['p95']} ms; "
200
+ f"tokens/call {rep['tokens_per_call']['input']}/{rep['tokens_per_call']['output']}; "
201
+ f"est. cost ${rep['cost_usd_per_1k_decisions']}/1k decisions; escalation rate {rep['escalation_rate']}", "",
202
+ "| question | n | acc | ECE raw | ECE after fit | acc (test, after fit) | acc automated | n automated | top errors |",
203
+ "|---|---:|---:|---:|---:|---:|---:|---:|---|"]
204
+ for qid, q in rep["questions"].items():
205
+ a, tr, tc, au = q["all"], q["test_raw"], q["test_recalibrated"], q["automated_subset"]
206
+ errs = ", ".join(f"{k} ({v})" for k, v in q["top_errors"].items())
207
+ L.append(f"| {qid} | {a['n']} | {a['accuracy']} | {tr.get('ece', '-')} | {tc.get('ece', '-')} | {tc.get('accuracy', '-')} | "
208
+ f"{au.get('accuracy', '-')} | {au.get('n', 0)} | {errs} |")
209
+ langs = sorted({l for q in rep["questions"].values() for l in q["by_lang"]})
210
+ if len(langs) > 1:
211
+ L += ["", "| question | " + " | ".join(f"acc {l}" for l in langs) + " |", "|---|" + "---:|" * len(langs)]
212
+ for qid, q in rep["questions"].items():
213
+ L.append(f"| {qid} | " + " | ".join(str(q["by_lang"].get(l, {}).get("accuracy", "-")) for l in langs) + " |")
214
+ return "\n".join(L)
215
+
216
+
217
+ def main(argv=None):
218
+ ap = argparse.ArgumentParser()
219
+ ap.add_argument("--block", required=True)
220
+ ap.add_argument("--backend", required=True)
221
+ ap.add_argument("--model", default=None)
222
+ ap.add_argument("--data", required=True)
223
+ ap.add_argument("--ensemble", type=int, default=1)
224
+ ap.add_argument("--limit", type=int, default=None)
225
+ ap.add_argument("--out", default=None, help="directory for JSON + markdown results")
226
+ ap.add_argument("--verbose", action="store_true")
227
+ ap.add_argument("--split", choices=["train", "test"], default=None, help="evaluate only this half of the rows")
228
+ ap.add_argument("--tag", default=None, help="suffix for the result file name, e.g. the checkpoint name")
229
+ a = ap.parse_args(argv)
230
+ block, backend, data = get_block(a.block), get_backend(a.backend, a.model), load_jsonl(a.data)
231
+ rep = evaluate(block, backend, data, ensemble=a.ensemble, limit=a.limit, verbose=a.verbose, split=a.split)
232
+ rep["split"] = a.split
233
+ if a.model:
234
+ rep["model"] = a.model
235
+ md = to_markdown(rep)
236
+ print(md)
237
+ if a.out:
238
+ os.makedirs(a.out, exist_ok=True)
239
+ stem = f"{a.block}__{rep['backend'].replace(':', '-').replace('/', '-')}" + (f"__ens{a.ensemble}" if a.ensemble > 1 else "")
240
+ stem += (f"__{a.tag}" if a.tag else "") + (f"__{a.split}" if a.split else "")
241
+ with open(os.path.join(a.out, stem + ".json"), "w", encoding="utf-8") as f:
242
+ json.dump(rep, f, ensure_ascii=False, indent=1)
243
+ with open(os.path.join(a.out, stem + ".md"), "w", encoding="utf-8") as f:
244
+ f.write(md + "\n")
245
+ print(f"\nwrote {a.out}/{stem}.json and .md")
246
+
247
+
248
+ if __name__ == "__main__":
249
+ main()
jevblock/flywheel.py ADDED
@@ -0,0 +1,141 @@
1
+ """Phase 4 flywheel: turn classified memories and labelled rows into Laya training items.
2
+
3
+ Two sources, one output format (the Laya fine-tuning notebook's item shape):
4
+
5
+ {"ids": [...], "markers": [...], "qtype": 0|1|2, "target": [p0, p1, ...], "label": int,
6
+ "block": "memory.typing@v1:...", "qid": "block_type", "origin": "llm|gold|user"}
7
+
8
+ Sources:
9
+ * `rows_from_memblock(mem, block)`: every stored block carrying `custom_metadata["_classifier"]`
10
+ whose decision was escalated and answered by the LLM (`_classifier.llm`), or corrected by a
11
+ user (`_classifier.correction`, written by your app). The LLM/user answer is the target.
12
+ * `rows_from_jsonl(path, block)`: the Phase 2 labelled sets; the gold column is the target.
13
+
14
+ Targets are one-hot on the label. Soft targets (probability rows) are accepted when the source
15
+ provides them (`_classifier.llm_probabilities` or a `gold_probabilities` column).
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ from typing import Any, Iterable
22
+
23
+ from jevblock.criteria import JevBlock
24
+
25
+ QTYPES = {"choice": 0, "score": 1, "noul": 2}
26
+
27
+
28
+ def _option_keys(q: dict[str, Any]) -> list[str]:
29
+ if q["type"] == "choice":
30
+ return list(q["criteria"].keys())
31
+ if q["type"] == "score":
32
+ return [str(i) for i in range(len(q["criteria"]))]
33
+ return ["false", "true"]
34
+
35
+
36
+ def _target(q: dict[str, Any], label: str | None, probs: dict[str, float] | None) -> list[float] | None:
37
+ keys = _option_keys(q)
38
+ if probs:
39
+ t = [max(0.0, float(probs.get(k, 0.0))) for k in keys]
40
+ s = sum(t)
41
+ return [v / s for v in t] if s > 0 else None
42
+ if label is None or str(label) not in keys:
43
+ return None
44
+ return [1.0 if k == str(label) else 0.0 for k in keys]
45
+
46
+
47
+ def training_examples(block: JevBlock, state: Any, labels: dict[str, Any], probs: dict[str, dict[str, float]] | None = None,
48
+ origin: str = "gold") -> list[dict[str, Any]]:
49
+ """Untokenized examples: one per (state, question) with a label. Tokenize with `tokenize_examples`."""
50
+ out = []
51
+ qs = block.to_laya_questions()
52
+ for qid, q in qs.items():
53
+ if qid not in labels and not (probs and qid in probs):
54
+ continue
55
+ t = _target(q, labels.get(qid), (probs or {}).get(qid))
56
+ if t is None:
57
+ continue
58
+ out.append({"state": state, "qid": qid, "question": q, "target": t, "label": int(max(range(len(t)), key=t.__getitem__)),
59
+ "block": block.fingerprint(), "origin": origin})
60
+ return out
61
+
62
+
63
+ def rows_from_jsonl(path: str, block: JevBlock, split: str | None = None) -> list[dict[str, Any]]:
64
+ """Phase 2 labelled rows -> examples. `split` = "train" (even rows) | "test" (odd rows) | None."""
65
+ out = []
66
+ with open(path, encoding="utf-8") as f:
67
+ for i, line in enumerate(f):
68
+ if not line.strip():
69
+ continue
70
+ if split == "train" and i % 2 == 1:
71
+ continue
72
+ if split == "test" and i % 2 == 0:
73
+ continue
74
+ r = json.loads(line)
75
+ out += training_examples(block, r["state"], r["gold"], r.get("gold_probabilities"), origin="gold")
76
+ return out
77
+
78
+
79
+ def rows_from_memblock(mem, block: JevBlock, *, include_unescalated: bool = False, limit: int = 100_000) -> list[dict[str, Any]]:
80
+ """Escalation pairs and user corrections from a MemBlock instance.
81
+
82
+ For each block with `_classifier` metadata:
83
+ * `_classifier.correction` (dict qid -> label), if your app wrote one, wins (origin "user");
84
+ * else `_classifier.llm` (the escalation answer) is mapped onto the block's questions (origin "llm");
85
+ * else, with `include_unescalated=True`, the applied fields themselves (origin "self"), which
86
+ is only useful for distillation into a smaller checkpoint, not for improving accuracy.
87
+ """
88
+ from memblock.classifier import CLASSIFIER_METADATA_KEY # lazy import
89
+
90
+ out = []
91
+ for b in mem.query(limit=limit):
92
+ meta = (b.metadata.custom_metadata or {}).get(CLASSIFIER_METADATA_KEY)
93
+ if not meta:
94
+ continue
95
+ state = {"content": b.content}
96
+ if meta.get("correction"):
97
+ out += training_examples(block, state, meta["correction"], origin="user")
98
+ elif meta.get("llm"):
99
+ llm = meta["llm"]
100
+ labels = {}
101
+ if "type" in llm:
102
+ labels["block_type"] = llm["type"]
103
+ if "source" in llm:
104
+ labels["source"] = llm["source"]
105
+ if llm.get("encryption_level") == "sensitive" and "sensitivity" in block.questions:
106
+ pass # category unknown from the 4-field escalation prompt; skip rather than guess
107
+ out += training_examples(block, state, labels, origin="llm")
108
+ elif include_unescalated and meta.get("applied"):
109
+ ap = meta["applied"]
110
+ labels = {k2: ap[k1] for k1, k2 in (("type", "block_type"), ("source", "source")) if k1 in ap}
111
+ out += training_examples(block, state, labels, origin="self")
112
+ return out
113
+
114
+
115
+ def tokenize_examples(examples: Iterable[dict[str, Any]], tok, cfg: dict[str, Any]) -> list[dict[str, Any]]:
116
+ """Examples -> Laya training items using laya.common.build_sequence (PyTorch Laya package)."""
117
+ from laya.common import build_sequence, render_options # type: ignore
118
+
119
+ items = []
120
+ for ex in examples:
121
+ q = ex["question"]
122
+ crit = q.get("criteria")
123
+ if q["type"] == "choice" and isinstance(crit, list):
124
+ crit = {c: None for c in crit}
125
+ internal = {"t": q["type"], "ins": q["instructions"], "crit": crit}
126
+ seq, markers = build_sequence(tok, ex["state"], internal, cfg.get("max_len", 512), cfg.get("head_max_len", 192))
127
+ if len(markers) != len(render_options(internal)) or len(markers) != len(ex["target"]):
128
+ continue
129
+ items.append({"ids": seq, "markers": markers, "qtype": QTYPES[q["type"]], "target": ex["target"],
130
+ "label": ex["label"], "block": ex["block"], "qid": ex["qid"], "origin": ex["origin"]})
131
+ return items
132
+
133
+
134
+ def summarize(examples: list[dict[str, Any]]) -> dict[str, Any]:
135
+ by = {}
136
+ for ex in examples:
137
+ k = f'{ex["block"].split("@")[0]}.{ex["qid"]}'
138
+ by.setdefault(k, {"n": 0, "origins": {}})
139
+ by[k]["n"] += 1
140
+ by[k]["origins"][ex["origin"]] = by[k]["origins"].get(ex["origin"], 0) + 1
141
+ return by
jevblock/llm.py ADDED
@@ -0,0 +1,114 @@
1
+ """Shared machinery for generative-LLM backends.
2
+
3
+ A block's questions are rendered into one structured-output request that asks the model for
4
+ the full probability distribution per question. The reply is normalised into the same answer
5
+ payload Jev / Laya return, so bindings, gates, chaining and calibration are backend-agnostic.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import math
12
+ from typing import Any
13
+
14
+ SYSTEM_PROMPT = (
15
+ "You are a System One decision engine. You do not chat or explain. For every question you are "
16
+ "given about the state, you return a probability distribution over the listed options. "
17
+ "Probabilities must be honest: spread them when the state is ambiguous, concentrate them only "
18
+ "when the evidence is clear. Each question is independent; answer all of them. "
19
+ "Return only the JSON object required by the schema."
20
+ )
21
+
22
+
23
+ def render_question(qid: str, q: dict[str, Any]) -> str:
24
+ t = q["type"]
25
+ lines = [f'Question "{qid}" ({t}): {q["instructions"]}']
26
+ crit = q.get("criteria")
27
+ if t == "choice":
28
+ for k, v in crit.items():
29
+ lines.append(f" - {k}" + (f": {v}" if v not in (None, "") else ""))
30
+ elif t == "score":
31
+ for i, lvl in enumerate(crit):
32
+ lines.append(f" - level {i}: {lvl}")
33
+ else:
34
+ crit = crit or {}
35
+ lines.append(" - true: " + (crit.get("true") or "yes, the statement holds"))
36
+ lines.append(" - false: " + (crit.get("false") or "no, the statement does not hold"))
37
+ return "\n".join(lines)
38
+
39
+
40
+ def public_state(state: Any) -> Any:
41
+ """Drop private keys (leading underscore) that radars use but engines must not see."""
42
+ if isinstance(state, dict):
43
+ return {k: v for k, v in state.items() if not str(k).startswith("_")}
44
+ return state
45
+
46
+
47
+ def render_user_prompt(state: Any, questions: dict[str, dict[str, Any]]) -> str:
48
+ state = public_state(state)
49
+ state_text = state if isinstance(state, str) else json.dumps(state, ensure_ascii=False, indent=None)
50
+ body = "\n\n".join(render_question(qid, q) for qid, q in questions.items())
51
+ return f"STATE:\n{state_text}\n\nQUESTIONS:\n{body}\n\nReturn probabilities for every option of every question."
52
+
53
+
54
+ def option_keys(q: dict[str, Any]) -> list[str]:
55
+ t = q["type"]
56
+ if t == "choice":
57
+ return list(q["criteria"].keys())
58
+ if t == "score":
59
+ return [str(i) for i in range(len(q["criteria"]))]
60
+ return ["false", "true"]
61
+
62
+
63
+ def json_schema(questions: dict[str, dict[str, Any]]) -> dict[str, Any]:
64
+ """One object per question, each with a fixed set of numeric option fields."""
65
+ props: dict[str, Any] = {}
66
+ for qid, q in questions.items():
67
+ keys = option_keys(q)
68
+ props[qid] = {
69
+ "type": "object",
70
+ "properties": {k: {"type": "number", "minimum": 0, "maximum": 1} for k in keys},
71
+ "required": keys,
72
+ "additionalProperties": False,
73
+ }
74
+ return {"type": "object", "properties": props, "required": list(questions), "additionalProperties": False}
75
+
76
+
77
+ def _confidence(p: list[float]) -> float:
78
+ k = len(p)
79
+ if k < 2:
80
+ return 1.0
81
+ ent = -sum(v * math.log(max(v, 1e-12)) for v in p)
82
+ return max(0.0, min(1.0, 1.0 - ent / math.log(k)))
83
+
84
+
85
+ def normalise(raw: dict[str, Any], questions: dict[str, dict[str, Any]]) -> dict[str, Any]:
86
+ """Turn the model's {qid: {option: weight}} into the Jev/Laya answer payload."""
87
+ answers: dict[str, Any] = {}
88
+ for qid, q in questions.items():
89
+ keys = option_keys(q)
90
+ got = raw.get(qid) or {}
91
+ w = [max(0.0, float(got.get(k, 0.0) or 0.0)) for k in keys]
92
+ s = sum(w)
93
+ p = [v / s for v in w] if s > 0 else [1.0 / len(keys)] * len(keys)
94
+ conf = round(_confidence(p), 4)
95
+ t = q["type"]
96
+ if t == "choice":
97
+ answers[qid] = {"type": "choice", "choice": keys[max(range(len(p)), key=p.__getitem__)],
98
+ "probabilities": {k: round(v, 4) for k, v in zip(keys, p)}, "confidence": conf}
99
+ elif t == "score":
100
+ answers[qid] = {"type": "score", "score": round(sum(i * v for i, v in enumerate(p)), 4),
101
+ "legend": {str(i): c for i, c in enumerate(q["criteria"])},
102
+ "probabilities": {k: round(v, 4) for k, v in zip(keys, p)}, "confidence": conf}
103
+ else:
104
+ answers[qid] = {"type": "noul", "noul": round(p[1], 4), "confidence": round(max(p[1], 1 - p[1]), 4)}
105
+ return answers
106
+
107
+
108
+ def parse_json_text(text: str) -> dict[str, Any]:
109
+ text = text.strip()
110
+ if text.startswith("```"):
111
+ text = text.strip("`")
112
+ if text.startswith("json"):
113
+ text = text[4:]
114
+ return json.loads(text)
jevblock/log.py ADDED
@@ -0,0 +1,79 @@
1
+ """Standalone decision log: every decision JevBlock makes, appended as one JSON line.
2
+
3
+ This is the flywheel's data source when JevBlock runs on its own (no MemBlock). Corrections are
4
+ appended as separate lines that reference the decision id, so the log is append-only and
5
+ auditable, and `rows_from_log` prefers the latest correction over the model's answer.
6
+
7
+ log = DecisionLog("decisions.jsonl")
8
+ clf = JevBlockClassifier(backend, blocks, log=log) # or log.record(decision, state) yourself
9
+ log.correct(decision_id, {"intent": "complaint"}) # a human or a stronger model fixed it
10
+ rows = rows_from_log("decisions.jsonl", block) # -> flywheel training examples
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import os
17
+ import time
18
+ import uuid
19
+ from typing import Any, Iterable
20
+
21
+ from jevblock.criteria import JevBlock
22
+
23
+
24
+ class DecisionLog:
25
+ def __init__(self, path: str):
26
+ self.path = path
27
+ os.makedirs(os.path.dirname(os.path.abspath(path)) or ".", exist_ok=True)
28
+
29
+ def _append(self, rec: dict[str, Any]) -> None:
30
+ with open(self.path, "a", encoding="utf-8") as f:
31
+ f.write(json.dumps(rec, ensure_ascii=False) + "\n")
32
+
33
+ def record(self, decision, state: Any, tags: dict[str, Any] | None = None) -> str:
34
+ did = uuid.uuid4().hex[:12]
35
+ self._append({"kind": "decision", "id": did, "ts": time.time(), "state": state,
36
+ "block": decision.fingerprint, "backend": decision.backend,
37
+ "answers": {q: {k: v for k, v in a.items() if k in ("choice", "score", "noul", "probabilities", "confidence")}
38
+ for q, a in decision.answers.items()},
39
+ "fields": decision.fields, "escalate": decision.escalate, "latency_ms": round(decision.latency_ms, 1),
40
+ "tags": tags or {}})
41
+ return did
42
+
43
+ def correct(self, decision_id: str, labels: dict[str, Any], by: str = "user") -> None:
44
+ """labels: {qid: gold label} — the corrected answer for one or more of the decision's questions."""
45
+ self._append({"kind": "correction", "id": decision_id, "ts": time.time(), "labels": labels, "by": by})
46
+
47
+ def read(self) -> Iterable[dict[str, Any]]:
48
+ if not os.path.exists(self.path):
49
+ return []
50
+ with open(self.path, encoding="utf-8") as f:
51
+ return [json.loads(l) for l in f if l.strip()]
52
+
53
+
54
+ def rows_from_log(path: str, block: JevBlock, *, include_uncorrected: bool = False) -> list[dict[str, Any]]:
55
+ """Training examples for `block` from a decision log.
56
+
57
+ Corrected decisions become gold rows (origin "user" or the corrector's name). Uncorrected
58
+ ones are included only with `include_uncorrected=True` (origin "self": the model's own answer,
59
+ useful for distillation into a smaller backend, not for improving accuracy).
60
+ """
61
+ from jevblock.flywheel import training_examples
62
+
63
+ entries = DecisionLog(path).read()
64
+ decisions = {e["id"]: e for e in entries if e["kind"] == "decision" and e["block"].split("@")[0] == block.id}
65
+ corrections: dict[str, tuple[dict[str, Any], str]] = {}
66
+ for e in entries:
67
+ if e["kind"] == "correction" and e["id"] in decisions:
68
+ prev = corrections.get(e["id"], ({}, "user"))[0]
69
+ corrections[e["id"]] = ({**prev, **e["labels"]}, e.get("by", "user"))
70
+ out = []
71
+ for did, d in decisions.items():
72
+ if did in corrections:
73
+ labels, by = corrections[did]
74
+ out += training_examples(block, d["state"], labels, origin=by)
75
+ elif include_uncorrected:
76
+ labels = {q: (a.get("choice") if "choice" in a else str(int(round(a["score"]))) if "score" in a
77
+ else ("true" if a["noul"] >= 0.5 else "false")) for q, a in d["answers"].items()}
78
+ out += training_examples(block, d["state"], labels, origin="self")
79
+ return out