jevzilla 0.1.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.
jevzilla/__init__.py ADDED
@@ -0,0 +1,294 @@
1
+ """
2
+ JEVzilla - a tiny, fearless client for JEV.
3
+
4
+ You write payloads exactly like the JEV API docs (https://jevplayground.com/jev-api):
5
+
6
+ {"state": "...", "questions": {"urgent": {"type": "noul", "instructions": "..."}}}
7
+
8
+ Question types follow the docs: noul (alias: boolean), choice, score.
9
+ Before sending, JEVzilla translates the payload to the wire format the
10
+ playground endpoint (/api/evaluate) expects:
11
+
12
+ noul, no criteria -> {"instructions", "type": "boolean"}
13
+ noul, with criteria -> {"instructions", "type": "choice", "criteria": {"true": ..., "false": ...}}
14
+ choice -> {"instructions", "type": "choice", "criteria": {label: description}}
15
+ score -> {"instructions", "type": "score", "criteria": [level, ...]}
16
+
17
+ state (str / dict / list) -> always a string on the playground wire.
18
+
19
+ backend="typesafe" instead sends the docs format as-is to the official
20
+ endpoint (POST https://api.typesafe.ai/v1/systemone) with a Bearer API key.
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import copy
25
+ import json
26
+ import os
27
+ import random
28
+ import time
29
+ from dataclasses import dataclass, field
30
+ from typing import Any, Dict, Optional, Sequence, Tuple
31
+
32
+ import requests
33
+
34
+ __all__ = [
35
+ "JEVzilla", "JEVResponse", "JEVError", "JEVValidationError", "JEVHTTPError",
36
+ "to_playground_payload", "to_typesafe_payload",
37
+ "noul", "choice", "score", "Noul", "Choice", "Score",
38
+ ]
39
+ __version__ = "0.3.0"
40
+
41
+ PLAYGROUND_URL = "https://jevplayground.com/api/evaluate"
42
+ TYPESAFE_URL = "https://api.typesafe.ai/v1/systemone"
43
+ OPENROUTER_URL = "https://openrouter.ai/api/alpha/decisions"
44
+ _ORIGIN = "https://jevplayground.com"
45
+ _RETRY_STATUSES = {429, 502, 503, 504, 529}
46
+
47
+ # docs-style type names accepted on input -> canonical
48
+ _TYPE_ALIASES = {
49
+ "noul": "noul", "boolean": "noul", "bool": "noul",
50
+ "choice": "choice",
51
+ "score": "score",
52
+ }
53
+
54
+
55
+ class JEVError(Exception):
56
+ """Base error for JEVzilla."""
57
+
58
+
59
+ class JEVValidationError(JEVError, ValueError):
60
+ """Payload could not be translated into a valid JEV request."""
61
+
62
+
63
+ class JEVHTTPError(JEVError):
64
+ def __init__(self, status_code: int, body: str):
65
+ super().__init__(f"JEV API returned HTTP {status_code}: {body[:300]}")
66
+ self.status_code = status_code
67
+ self.body = body
68
+
69
+
70
+ # ------------------------------------------------- docs-style builders
71
+ def noul(instructions: str, criteria: Optional[Dict[str, str]] = None) -> Dict[str, Any]:
72
+ q: Dict[str, Any] = {"type": "noul", "instructions": instructions}
73
+ if criteria is not None:
74
+ q["criteria"] = criteria
75
+ return q
76
+
77
+
78
+ def choice(instructions: str, criteria: Dict[str, str]) -> Dict[str, Any]:
79
+ return {"type": "choice", "instructions": instructions, "criteria": criteria}
80
+
81
+
82
+ def score(instructions: str, criteria: Sequence[str]) -> Dict[str, Any]:
83
+ return {"type": "score", "instructions": instructions, "criteria": list(criteria)}
84
+
85
+
86
+ Noul, Choice, Score = noul, choice, score # mirror the SDK's capitalized names
87
+
88
+
89
+ # ------------------------------------------------------ parsing (docs style)
90
+ def _parse_question(name: str, q: Any) -> Tuple[str, str, Any]:
91
+ """Validate one docs-style question -> (canonical type, instructions, criteria)."""
92
+ where = f"questions[{name!r}]"
93
+ if not isinstance(q, dict):
94
+ raise JEVValidationError(f"{where} must be an object")
95
+
96
+ instructions = q.get("instructions")
97
+ if not isinstance(instructions, str) or not instructions.strip():
98
+ raise JEVValidationError(f"{where}.instructions must be a non-empty string")
99
+
100
+ raw = q.get("type")
101
+ qtype = _TYPE_ALIASES.get(str(raw).strip().lower()) if raw is not None else None
102
+ if qtype is None:
103
+ raise JEVValidationError(f"{where}.type must be one of noul | boolean | choice | score (got {raw!r})")
104
+
105
+ criteria = q.get("criteria")
106
+
107
+ if qtype == "noul":
108
+ if criteria in (None, {}, []):
109
+ return qtype, instructions, None
110
+ if not isinstance(criteria, dict):
111
+ raise JEVValidationError(f"{where}.criteria for 'noul' must be an object like {{'true': ..., 'false': ...}}")
112
+ return qtype, instructions, {str(k): str(v) for k, v in criteria.items()}
113
+
114
+ if qtype == "choice":
115
+ if isinstance(criteria, dict) and criteria:
116
+ return qtype, instructions, {str(k): str(v) for k, v in criteria.items()}
117
+ if isinstance(criteria, (list, tuple)) and criteria: # lenient: ["a","b"] -> {"a":"a","b":"b"}
118
+ return qtype, instructions, {str(c): str(c) for c in criteria}
119
+ raise JEVValidationError(f"{where}.criteria must be a non-empty object for 'choice'")
120
+
121
+ # score
122
+ if isinstance(criteria, (list, tuple)) and criteria:
123
+ return qtype, instructions, [str(c) for c in criteria]
124
+ raise JEVValidationError(f"{where}.criteria must be a non-empty list of levels for 'score'")
125
+
126
+
127
+ def _parse_payload(payload: Dict[str, Any]) -> Tuple[Any, Dict[str, Tuple[str, str, Any]]]:
128
+ if not isinstance(payload, dict):
129
+ raise JEVValidationError("payload must be a dict")
130
+ state = payload.get("state")
131
+ if state is None or (isinstance(state, str) and not state.strip()) or state in ({}, []):
132
+ raise JEVValidationError("payload.state must be a non-empty string, object or array")
133
+ if not isinstance(state, (str, dict, list)):
134
+ raise JEVValidationError("payload.state must be a string, object or array")
135
+ questions = payload.get("questions")
136
+ if not isinstance(questions, dict) or not questions:
137
+ raise JEVValidationError("payload.questions must be a non-empty dict")
138
+ parsed = {str(n): _parse_question(str(n), copy.deepcopy(q)) for n, q in questions.items()}
139
+ return state, parsed
140
+
141
+
142
+ # ------------------------------------------------------------- translators
143
+ def to_playground_payload(payload: Dict[str, Any]) -> Dict[str, Any]:
144
+ """docs-style payload -> the exact shape /api/evaluate expects."""
145
+ state, parsed = _parse_payload(payload)
146
+ if not isinstance(state, str):
147
+ state = json.dumps(state, ensure_ascii=False, indent=2)
148
+
149
+ questions: Dict[str, Any] = {}
150
+ for name, (qtype, instructions, criteria) in parsed.items():
151
+ if qtype == "noul":
152
+ if criteria is None:
153
+ questions[name] = {"instructions": instructions, "type": "boolean"}
154
+ else: # true/false criteria -> the "choice" shape from the working example
155
+ questions[name] = {"instructions": instructions, "type": "choice", "criteria": criteria}
156
+ else: # choice / score pass through
157
+ questions[name] = {"instructions": instructions, "type": qtype, "criteria": criteria}
158
+ return {"state": state, "questions": questions}
159
+
160
+
161
+ def to_typesafe_payload(payload: Dict[str, Any], model: str = "jev-latest") -> Dict[str, Any]:
162
+ """docs-style payload -> validated body for the official /v1/systemone endpoint."""
163
+ state, parsed = _parse_payload(payload)
164
+ questions: Dict[str, Any] = {}
165
+ for name, (qtype, instructions, criteria) in parsed.items():
166
+ q = {"type": qtype, "instructions": instructions}
167
+ if criteria is not None:
168
+ q["criteria"] = criteria
169
+ questions[name] = q
170
+ return {"model": model, "state": state, "questions": questions}
171
+
172
+
173
+ # ------------------------------------------------------------------ client
174
+ @dataclass
175
+ class JEVResponse:
176
+ status_code: int
177
+ text: str
178
+ data: Any = None
179
+ request: Dict[str, Any] = field(default_factory=dict) # the body actually sent
180
+
181
+ @property
182
+ def ok(self) -> bool:
183
+ return 200 <= self.status_code < 300
184
+
185
+ @property
186
+ def answers(self) -> Any:
187
+ """`data["answers"]` when present (official shape), else the raw parsed body."""
188
+ if isinstance(self.data, dict) and "answers" in self.data:
189
+ return self.data["answers"]
190
+ return self.data
191
+
192
+ def __getitem__(self, key):
193
+ return self.answers[key]
194
+
195
+ # ---- convenience readers for the real answer shapes ----
196
+ def noul(self, key: str, threshold: float = 0.5) -> bool:
197
+ """True/False reading of a noul answer (backend returns a 0-1 probability)."""
198
+ return self.answers[key]["noul"] >= threshold
199
+
200
+ def choice(self, key: str) -> str:
201
+ return self.answers[key]["choice"]
202
+
203
+ def score_label(self, key: str) -> str:
204
+ a = self.answers[key]
205
+ return a["legend"][str(round(a["score"]))]
206
+
207
+
208
+ class JEVzilla:
209
+ """
210
+ >>> jev = JEVzilla() # playground endpoint
211
+ >>> jev.evaluate({
212
+ ... "state": "The customer says their production service is down.",
213
+ ... "questions": {"urgent": {"type": "noul", "instructions": "Is this request urgent?"}},
214
+ ... })
215
+
216
+ >>> jev = JEVzilla(backend="typesafe") # official API, reads TYPESAFE_API_KEY
217
+ """
218
+
219
+ def __init__(self, backend: str = "playground", api_key: Optional[str] = None,
220
+ model: str = "jev-latest", url: Optional[str] = None, timeout: float = 30.0,
221
+ retries: int = 4, backoff: float = 1.0, max_backoff: float = 30.0,
222
+ session: Optional[requests.Session] = None,
223
+ extra_headers: Optional[Dict[str, str]] = None):
224
+ if backend not in ("playground", "typesafe", "openrouter"):
225
+ raise ValueError("backend must be 'playground', 'typesafe' or 'openrouter'")
226
+ self.backend, self.model, self.timeout = backend, model, timeout
227
+ self.retries, self.backoff, self.max_backoff = max(0, retries), backoff, max_backoff
228
+ self.session = session or requests.Session()
229
+ if backend == "playground":
230
+ self.url = url or PLAYGROUND_URL
231
+ self.headers = {"Content-Type": "application/json", "Origin": _ORIGIN, "Referer": _ORIGIN + "/"}
232
+ elif backend == "typesafe":
233
+ key = api_key or os.environ.get("TYPESAFE_API_KEY")
234
+ if not key:
235
+ raise JEVError("backend='typesafe' needs api_key= or the TYPESAFE_API_KEY env var")
236
+ self.url = url or TYPESAFE_URL
237
+ self.headers = {"Content-Type": "application/json", "Authorization": f"Bearer {key}"}
238
+ else: # openrouter
239
+ key = api_key or os.environ.get("OPENROUTER_API_KEY")
240
+ if not key:
241
+ raise JEVError("backend='openrouter' needs api_key= or the OPENROUTER_API_KEY env var")
242
+ self.url = url or OPENROUTER_URL
243
+ self.model = model if model != "jev-latest" else "typesafe/jev-1.13"
244
+ self.headers = {"Content-Type": "application/json", "Authorization": f"Bearer {key}"}
245
+ self.headers.update(extra_headers or {})
246
+
247
+ def build(self, payload: Dict[str, Any]) -> Dict[str, Any]:
248
+ """The exact body that would be sent, without sending it."""
249
+ if self.backend == "playground":
250
+ return to_playground_payload(payload)
251
+ return to_typesafe_payload(payload, self.model)
252
+
253
+ def _sleep_time(self, attempt: int, resp: Optional[requests.Response]) -> float:
254
+ if resp is not None:
255
+ ra = resp.headers.get("Retry-After")
256
+ if ra and ra.replace(".", "", 1).isdigit():
257
+ return min(float(ra), self.max_backoff)
258
+ return min(self.backoff * (2 ** attempt), self.max_backoff) * random.uniform(0.75, 1.25)
259
+
260
+ def evaluate(self, payload: Dict[str, Any], raise_for_status: bool = True) -> JEVResponse:
261
+ """POST the translated payload. Retries transient failures (429/502/503/504/529,
262
+ timeouts, connection errors) with exponential backoff; 4xx like 401/422 are not retried."""
263
+ body = self.build(payload)
264
+ r: Optional[requests.Response] = None
265
+ for attempt in range(self.retries + 1):
266
+ try:
267
+ r = self.session.post(self.url, json=body, headers=self.headers, timeout=self.timeout)
268
+ except (requests.ConnectionError, requests.Timeout):
269
+ if attempt == self.retries:
270
+ raise
271
+ time.sleep(self._sleep_time(attempt, None))
272
+ continue
273
+ if r.status_code in _RETRY_STATUSES and attempt < self.retries:
274
+ time.sleep(self._sleep_time(attempt, r))
275
+ continue
276
+ break
277
+ try:
278
+ data = r.json()
279
+ except ValueError:
280
+ data = None
281
+ res = JEVResponse(r.status_code, r.text, data, body)
282
+ if raise_for_status and not res.ok:
283
+ raise JEVHTTPError(r.status_code, r.text)
284
+ return res
285
+
286
+ # single-question shortcuts (answer key defaults to "decision")
287
+ def ask_noul(self, state, instructions, criteria=None, key="decision", **kw) -> JEVResponse:
288
+ return self.evaluate({"state": state, "questions": {key: noul(instructions, criteria)}}, **kw)
289
+
290
+ def ask_choice(self, state, instructions, criteria, key="decision", **kw) -> JEVResponse:
291
+ return self.evaluate({"state": state, "questions": {key: choice(instructions, criteria)}}, **kw)
292
+
293
+ def ask_score(self, state, instructions, levels, key="decision", **kw) -> JEVResponse:
294
+ return self.evaluate({"state": state, "questions": {key: score(instructions, levels)}}, **kw)
@@ -0,0 +1,8 @@
1
+ Metadata-Version: 2.4
2
+ Name: jevzilla
3
+ Version: 0.1.0
4
+ Summary: A tiny, fearless client for the JEV evaluation API
5
+ Requires-Python: >=3.8
6
+ License-File: LICENSE
7
+ Requires-Dist: requests>=2.28
8
+ Dynamic: license-file
@@ -0,0 +1,6 @@
1
+ jevzilla/__init__.py,sha256=8NVhZ_iIRWr6aCugH0rkOB2ZTVDCtWhPUXufYXWe7ZA,13110
2
+ jevzilla-0.1.0.dist-info/licenses/LICENSE,sha256=uPGoWbFqVueZ5PvyMXfMQBWbuAnwJX898UPB6iMTXIw,1073
3
+ jevzilla-0.1.0.dist-info/METADATA,sha256=mLpliuJYwO1CombNq2iG0RKihTCHyUPtDyBzQ68zj4M,217
4
+ jevzilla-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
5
+ jevzilla-0.1.0.dist-info/top_level.txt,sha256=WhXJhjBAyEl7qdrWvxzVyWtsWkQPDci-6LtGmZp3phg,9
6
+ jevzilla-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Ujjwalkumar Soni
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ jevzilla