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/__init__.py ADDED
@@ -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
+ ]
jevblock/backends.py ADDED
@@ -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())
@@ -0,0 +1,63 @@
1
+ """Anthropic (Claude) backend for JevBlock.
2
+
3
+ One structured-output call per block. The model returns a distribution per question; the reply
4
+ is normalised into the Jev/Laya answer payload. Credentials come from the environment
5
+ (`ANTHROPIC_API_KEY` or an `ant auth login` profile); never pass keys through block files.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+
12
+ from jevblock.llm import SYSTEM_PROMPT, json_schema, normalise, parse_json_text, render_user_prompt
13
+
14
+
15
+ class AnthropicBackend:
16
+ name = "anthropic"
17
+
18
+ def __init__(self, model: str = "claude-opus-5", effort: str = "low", client: Any = None,
19
+ max_tokens: int = 2048, fallbacks: bool = True, timeout: float = 30.0):
20
+ """`effort` is low by default: classification does not benefit from deep thinking.
21
+
22
+ `fallbacks=True` enables Anthropic's server-side refusal fallback (beta) so a policy decline
23
+ is re-run on a fallback model inside the same call instead of returning an empty answer.
24
+ """
25
+ if client is None:
26
+ import anthropic
27
+ client = anthropic.Anthropic(timeout=timeout)
28
+ self._client = client
29
+ self._model = model
30
+ self._effort = effort
31
+ self._max_tokens = max_tokens
32
+ self._fallbacks = fallbacks
33
+ self.name = f"anthropic:{model}"
34
+
35
+ def predict(self, state: Any, questions: dict[str, dict[str, Any]]) -> dict[str, Any]:
36
+ kwargs: dict[str, Any] = dict(
37
+ model=self._model,
38
+ max_tokens=self._max_tokens,
39
+ system=[{"type": "text", "text": SYSTEM_PROMPT, "cache_control": {"type": "ephemeral"}}],
40
+ messages=[{"role": "user", "content": render_user_prompt(state, questions)}],
41
+ output_config={"effort": self._effort, "format": {"type": "json_schema", "schema": json_schema(questions)}},
42
+ )
43
+ if self._fallbacks:
44
+ response = self._client.beta.messages.create(
45
+ betas=["server-side-fallback-2026-07-01"], fallbacks="default", **kwargs
46
+ )
47
+ else:
48
+ response = self._client.messages.create(**kwargs)
49
+
50
+ if response.stop_reason == "refusal":
51
+ raise RuntimeError(f"{self.name}: request refused ({getattr(response, 'stop_details', None)})")
52
+ text = next(b.text for b in response.content if b.type == "text")
53
+ raw = parse_json_text(text)
54
+ usage = getattr(response, "usage", None)
55
+ return {
56
+ "model": self.name,
57
+ "answers": normalise(raw, questions),
58
+ "usage": {
59
+ "input_tokens": getattr(usage, "input_tokens", 0),
60
+ "output_tokens": getattr(usage, "output_tokens", 0),
61
+ "cache_read_input_tokens": getattr(usage, "cache_read_input_tokens", 0),
62
+ },
63
+ }
@@ -0,0 +1,169 @@
1
+ """Ollama backend for JevBlock: local open-weight LLMs (Gemma, Qwen, Llama...) at zero per-call cost.
2
+
3
+ Uses Ollama's native /api/chat with a JSON schema in `format`, so the model is constrained to
4
+ return exactly the per-question distributions the block asks for. Same answer payload as every
5
+ other backend; blocks, gates, calibration and the harness are unchanged.
6
+
7
+ from jevblock.backends_ollama import OllamaBackend
8
+ be = OllamaBackend(model="gemma4") # needs `ollama serve` running
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import time
15
+ import urllib.error
16
+ import urllib.request
17
+ from typing import Any
18
+
19
+ from jevblock.llm import SYSTEM_PROMPT, json_schema, normalise, parse_json_text, render_user_prompt
20
+
21
+
22
+ LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
23
+
24
+ LETTER_SYSTEM_PROMPT = (
25
+ "You are a decision engine. You will be shown a STATE and one question with lettered options. "
26
+ "Reply with exactly one capital letter, the letter of the best option. No words, no punctuation, no explanation."
27
+ )
28
+
29
+
30
+ class OllamaBackend:
31
+ """Three confidence modes, chosen with `mode=`:
32
+
33
+ * "distribution" (one call per block): the model writes a probability per option into a
34
+ JSON schema. Cheapest, but small local models are badly over-confident this way
35
+ (gemma4: ECE 0.53 to 0.65 measured).
36
+ * "logprobs" (one short call per question): ask for a single letter, read the model's own
37
+ token log-probabilities over the option letters. Native probabilities, no thinking.
38
+ * "vote" (N short calls per question): sample the letter N times at temperature > 0 and
39
+ use vote shares. Slowest; useful when the server has no logprobs.
40
+ """
41
+
42
+ name = "ollama"
43
+
44
+ def __init__(self, model: str = "gemma4:e2b", host: str = "http://localhost:11434", timeout: float = 120.0,
45
+ temperature: float = 0.0, num_ctx: int = 4096, keep_alive: str = "10m", think: bool | None = False,
46
+ mode: str = "logprobs", votes: int = 5):
47
+ if mode not in ("distribution", "logprobs", "vote"):
48
+ raise ValueError("mode must be distribution, logprobs or vote")
49
+ self._model, self._host, self._timeout = model, host.rstrip("/"), timeout
50
+ self._options = {"temperature": temperature, "num_ctx": num_ctx}
51
+ self._keep_alive, self._think, self._mode, self._votes = keep_alive, think, mode, votes
52
+ self.name = f"ollama:{model}" + ("" if mode == "distribution" else f":{mode}")
53
+
54
+ def _post(self, path: str, body: dict[str, Any]) -> dict[str, Any]:
55
+ req = urllib.request.Request(self._host + path, data=json.dumps(body).encode(), method="POST",
56
+ headers={"Content-Type": "application/json"})
57
+ last: Exception | None = None
58
+ for attempt in range(3): # the first request after a model load can 500 or time out
59
+ try:
60
+ with urllib.request.urlopen(req, timeout=self._timeout) as r:
61
+ return json.loads(r.read().decode())
62
+ except urllib.error.HTTPError as e:
63
+ last = e
64
+ if e.code < 500:
65
+ raise RuntimeError(f"{self.name}: Ollama returned {e.code}: {e.read()[:200]!r}") from e
66
+ except urllib.error.URLError as e:
67
+ last = e
68
+ time.sleep(2 * (attempt + 1))
69
+ raise RuntimeError(f"{self.name}: cannot get a response from Ollama at {self._host} ({last}); run `ollama serve`") from last
70
+
71
+ # ------------------------------------------------------------------ per-question letter modes
72
+ @staticmethod
73
+ def _letter_prompt(state: Any, qid: str, q: dict[str, Any]) -> tuple[str, list[str]]:
74
+ from jevblock.llm import option_keys, public_state, render_question
75
+ keys = option_keys(q)
76
+ state = public_state(state)
77
+ state_text = state if isinstance(state, str) else json.dumps(state, ensure_ascii=False)
78
+ q2 = dict(q)
79
+ if q["type"] == "choice":
80
+ q2["criteria"] = {f"{LETTERS[i]}) {k}": v for i, (k, v) in enumerate(q["criteria"].items())}
81
+ body = render_question(qid, q2)
82
+ elif q["type"] == "score":
83
+ lines = [f'Question "{qid}": {q["instructions"]}'] + [f" - {LETTERS[i]}) level {i}: {lvl}" for i, lvl in enumerate(q["criteria"])]
84
+ body = "\n".join(lines)
85
+ else:
86
+ crit = q.get("criteria") or {}
87
+ body = (f'Question "{qid}": {q["instructions"]}\n - A) false: ' + (crit.get("false") or "no, the statement does not hold")
88
+ + "\n - B) true: " + (crit.get("true") or "yes, the statement holds"))
89
+ prompt = f"STATE:\n{state_text}\n\n{body}\n\nAnswer with the single letter of the best option and nothing else."
90
+ return prompt, keys
91
+
92
+ def _letter_call(self, prompt: str, n_opts: int, temperature: float, logprobs: bool) -> tuple[str, dict[str, float]]:
93
+ body = {"model": self._model, "messages": [{"role": "system", "content": LETTER_SYSTEM_PROMPT}, {"role": "user", "content": prompt}],
94
+ "stream": False, "keep_alive": self._keep_alive, "think": False,
95
+ "options": {**self._options, "temperature": temperature, "num_predict": 3}}
96
+ if logprobs:
97
+ body["logprobs"] = True
98
+ body["top_logprobs"] = max(10, n_opts + 4)
99
+ resp = self._post("/api/chat", body)
100
+ text = ((resp.get("message") or {}).get("content") or "").strip()
101
+ lp: dict[str, float] = {}
102
+ valid = set(LETTERS[:n_opts])
103
+ for tokinfo in resp.get("logprobs") or []:
104
+ found: dict[str, float] = {}
105
+ for c in tokinfo.get("top_logprobs") or []:
106
+ t = c["token"].strip().rstrip(")").rstrip(".")
107
+ if len(t) == 1 and t.upper() in valid: # exactly one option letter, nothing else
108
+ L = t.upper()
109
+ found[L] = max(found.get(L, -1e9), c["logprob"])
110
+ if found:
111
+ lp = found
112
+ break
113
+ self._last_usage = {"input_tokens": resp.get("prompt_eval_count", 0), "output_tokens": resp.get("eval_count", 0)}
114
+ return text, lp
115
+
116
+ def _predict_letters(self, state: Any, questions: dict[str, dict[str, Any]]) -> dict[str, Any]:
117
+ import math
118
+ raw: dict[str, dict[str, float]] = {}
119
+ usage_in = usage_out = 0
120
+ for qid, q in questions.items():
121
+ prompt, keys = self._letter_prompt(state, qid, q)
122
+ n = len(keys)
123
+ if self._mode == "logprobs":
124
+ text, lp = self._letter_call(prompt, n, 0.0, True)
125
+ if lp:
126
+ m = max(lp.values())
127
+ w = {LETTERS[i]: math.exp(lp.get(LETTERS[i], -1e9) - m) for i in range(n)}
128
+ else: # no usable logprobs: fall back to the text answer as a hard vote
129
+ w = {LETTERS[i]: (1.0 if text[:1].upper() == LETTERS[i] else 1e-6) for i in range(n)}
130
+ else:
131
+ w = {LETTERS[i]: 0.0 for i in range(n)}
132
+ for _ in range(self._votes):
133
+ text, _ = self._letter_call(prompt, n, 0.8, False)
134
+ L = text[:1].upper()
135
+ if L in w:
136
+ w[L] += 1.0
137
+ if sum(w.values()) == 0:
138
+ w = {k: 1.0 for k in w}
139
+ raw[qid] = {keys[i]: w[LETTERS[i]] for i in range(n)}
140
+ usage_in += self._last_usage["input_tokens"]; usage_out += self._last_usage["output_tokens"]
141
+ return {"model": self.name, "answers": normalise(raw, questions),
142
+ "usage": {"input_tokens": usage_in, "output_tokens": usage_out, "calls": len(questions) * (1 if self._mode == "logprobs" else self._votes)}}
143
+
144
+ def predict(self, state: Any, questions: dict[str, dict[str, Any]]) -> dict[str, Any]:
145
+ if self._mode != "distribution":
146
+ return self._predict_letters(state, questions)
147
+ body: dict[str, Any] = {
148
+ "model": self._model,
149
+ "messages": [{"role": "system", "content": SYSTEM_PROMPT},
150
+ {"role": "user", "content": render_user_prompt(state, questions)}],
151
+ "format": json_schema(questions),
152
+ "stream": False,
153
+ "options": self._options,
154
+ "keep_alive": self._keep_alive,
155
+ }
156
+ if self._think is not None:
157
+ body["think"] = self._think
158
+ resp = self._post("/api/chat", body)
159
+ text = (resp.get("message") or {}).get("content") or "{}"
160
+ try:
161
+ raw = parse_json_text(text)
162
+ except json.JSONDecodeError:
163
+ raw = {}
164
+ return {
165
+ "model": self.name,
166
+ "answers": normalise(raw, questions),
167
+ "usage": {"input_tokens": resp.get("prompt_eval_count", 0), "output_tokens": resp.get("eval_count", 0),
168
+ "total_duration_ms": round(resp.get("total_duration", 0) / 1e6, 1)},
169
+ }
@@ -0,0 +1,86 @@
1
+ """OpenAI (ChatGPT) backend for JevBlock.
2
+
3
+ Two paths:
4
+ - `distribution` (default): one structured-output call per block; the model returns a
5
+ distribution per question.
6
+ - `logprobs`: for a block that is a single `choice` question, ask for one letter and read the
7
+ token log-probabilities directly. Probabilities then come from the model's own sampling
8
+ distribution rather than numbers it wrote, which is closer to what Jev/Laya return.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import math
14
+ import string
15
+ from typing import Any
16
+
17
+ from jevblock.llm import SYSTEM_PROMPT, json_schema, normalise, parse_json_text, render_question, render_user_prompt
18
+
19
+
20
+ class OpenAIBackend:
21
+ name = "openai"
22
+
23
+ def __init__(self, model: str = "gpt-5", client: Any = None, mode: str = "distribution",
24
+ max_tokens: int = 2048, timeout: float = 30.0):
25
+ if mode not in ("distribution", "logprobs"):
26
+ raise ValueError("mode must be 'distribution' or 'logprobs'")
27
+ if client is None:
28
+ import openai
29
+ client = openai.OpenAI(timeout=timeout)
30
+ self._client = client
31
+ self._model = model
32
+ self._mode = mode
33
+ self._max_tokens = max_tokens
34
+ self.name = f"openai:{model}"
35
+
36
+ # ------------------------------------------------------------------ public
37
+ def predict(self, state: Any, questions: dict[str, dict[str, Any]]) -> dict[str, Any]:
38
+ if self._mode == "logprobs":
39
+ single = list(questions.items())
40
+ if len(single) == 1 and single[0][1]["type"] == "choice" and len(single[0][1]["criteria"]) <= 26:
41
+ return self._predict_logprobs(state, *single[0])
42
+ return self._predict_distribution(state, questions)
43
+
44
+ # ------------------------------------------------------------------ distribution
45
+ def _predict_distribution(self, state, questions):
46
+ resp = self._client.chat.completions.create(
47
+ model=self._model,
48
+ messages=[{"role": "system", "content": SYSTEM_PROMPT},
49
+ {"role": "user", "content": render_user_prompt(state, questions)}],
50
+ response_format={"type": "json_schema",
51
+ "json_schema": {"name": "jevblock", "strict": True, "schema": json_schema(questions)}},
52
+ max_completion_tokens=self._max_tokens,
53
+ )
54
+ raw = parse_json_text(resp.choices[0].message.content or "{}")
55
+ usage = getattr(resp, "usage", None)
56
+ return {"model": self.name, "answers": normalise(raw, questions),
57
+ "usage": {"input_tokens": getattr(usage, "prompt_tokens", 0),
58
+ "output_tokens": getattr(usage, "completion_tokens", 0)}}
59
+
60
+ # ------------------------------------------------------------------ logprobs
61
+ def _predict_logprobs(self, state, qid, q):
62
+ keys = list(q["criteria"].keys())
63
+ letters = string.ascii_uppercase[: len(keys)]
64
+ lettered = {**q, "criteria": {f"{L}) {k}": v for L, (k, v) in zip(letters, q["criteria"].items())}}
65
+ prompt = (render_user_prompt(state, {qid: lettered})
66
+ .replace("Return probabilities for every option of every question.",
67
+ "Answer with the single letter of the best option and nothing else."))
68
+ resp = self._client.chat.completions.create(
69
+ model=self._model,
70
+ messages=[{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": prompt}],
71
+ max_completion_tokens=2, logprobs=True, top_logprobs=20,
72
+ )
73
+ top = resp.choices[0].logprobs.content[0].top_logprobs
74
+ lp = {L: -1e9 for L in letters}
75
+ for item in top:
76
+ tok = item.token.strip().upper().rstrip(")")
77
+ if tok in lp:
78
+ lp[tok] = max(lp[tok], item.logprob)
79
+ m = max(lp.values())
80
+ e = {L: math.exp(v - m) for L, v in lp.items()}
81
+ s = sum(e.values())
82
+ raw = {qid: {k: e[L] / s for L, k in zip(letters, keys)}}
83
+ usage = getattr(resp, "usage", None)
84
+ return {"model": self.name + ":logprobs", "answers": normalise(raw, {qid: q}),
85
+ "usage": {"input_tokens": getattr(usage, "prompt_tokens", 0),
86
+ "output_tokens": getattr(usage, "completion_tokens", 0)}}
jevblock/bindings.py ADDED
@@ -0,0 +1,50 @@
1
+ """Turn a block's answers into memory fields and actions. Pure application logic."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import operator
6
+ from typing import Any
7
+
8
+ from jevblock.criteria import Binding, Gate
9
+
10
+ _OPS = {"<": operator.lt, "<=": operator.le, ">": operator.gt, ">=": operator.ge, "==": operator.eq}
11
+
12
+
13
+ def read_source(answers: dict[str, Any], source: str) -> Any:
14
+ """Resolve "<qid>.<attr>" against the answers payload."""
15
+ qid, _, attr = source.partition(".")
16
+ a = answers[qid]
17
+ if attr.startswith("probabilities."):
18
+ return a["probabilities"][attr.split(".", 1)[1]]
19
+ if attr in ("", "value"):
20
+ attr = a["type"] # choice -> label, score -> expected level, noul -> P(true)
21
+ if attr == "level": # argmax level for score
22
+ probs = a["probabilities"]
23
+ return int(max(probs, key=probs.get))
24
+ return a[attr]
25
+
26
+
27
+ def resolve_bindings(answers: dict[str, Any], bindings: list[Binding]) -> dict[str, Any]:
28
+ out: dict[str, Any] = {}
29
+ for b in bindings:
30
+ val = read_source(answers, b.source)
31
+ if b.threshold is not None:
32
+ op, thr, if_true, if_false = b.threshold
33
+ val = if_true if _OPS[op](float(val), float(thr)) else if_false
34
+ elif b.map is not None:
35
+ key = val
36
+ if isinstance(val, float) and all(isinstance(k, int) or (isinstance(k, str) and k.isdigit()) for k in b.map):
37
+ key = int(round(val))
38
+ val = b.map.get(key, b.map.get(str(key), val))
39
+ out[b.field] = val
40
+ return out
41
+
42
+
43
+ def evaluate_gates(answers: dict[str, Any], gates: list[Gate]) -> list[tuple[Gate, Any]]:
44
+ """Return the gates that fired, with the value that triggered them."""
45
+ fired = []
46
+ for g in gates:
47
+ val = float(read_source(answers, g.source))
48
+ if _OPS[g.op](val, g.value):
49
+ fired.append((g, val))
50
+ return fired