basal-sdk 3.0.3__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.
basal_sdk/__init__.py ADDED
@@ -0,0 +1,21 @@
1
+ """basal-sdk: the Python client of basal-serve (POST /v1/systemone), its preset question sets and the agent-framework
2
+ adapters, with httpx as its only dependency (no torch, no model). basal-engine installs it at its own version, and
3
+ there basal.client, basal.presets and basal.adapters are these same modules.
4
+
5
+ from basal_sdk import Basal, choice, yes_no
6
+ b = Basal("http://127.0.0.1:8000")
7
+ b.decide(state, {"dept": choice("Which department?", {"billing": "Billing", "tech": "Technical support"}),
8
+ "urgent": yes_no("Is it urgent?")})
9
+
10
+ basal_sdk.client (Basal, AsyncBasal, the errors and question types), basal_sdk.presets (ready question sets, guard and
11
+ route), basal_sdk.adapters (LangChain, LlamaIndex, CrewAI tools)."""
12
+ from .client import (BUILTIN_RULE, AsyncBasal, AuthError, Basal, BasalError, Decision, InvalidRequest, NotReady,
13
+ OutOfMemory, QuestionError, ServerError, act, choice, classify, complete, compress, decision_of,
14
+ extract, fails_open, media_type, multi, rank, retryable, score, tool, verify, yes_no)
15
+
16
+ # basal-engine's: the two are released together (tests/test_versions.py)
17
+ __version__ = "3.0.3"
18
+ __all__ = ["BUILTIN_RULE", "AsyncBasal", "AuthError", "Basal", "BasalError", "Decision", "InvalidRequest", "NotReady",
19
+ "OutOfMemory", "QuestionError", "ServerError", "act", "choice", "classify", "complete", "compress",
20
+ "decision_of", "extract", "fails_open", "media_type", "multi", "rank", "retryable", "score", "tool",
21
+ "verify", "yes_no"]
basal_sdk/adapters.py ADDED
@@ -0,0 +1,75 @@
1
+ """Thin tools for agent frameworks over a running basal server's HTTP API (2.5). Each returns the framework's own tool
2
+ object that calls /v1/systemone: give it a state and questions (the HTTP API's), or fix a preset (basal_sdk.presets)
3
+ so the agent only passes the state. The frameworks are not dependencies of basal-sdk: install the one you use. For
4
+ MCP hosts use basal-engine's basal-mcp / basal-serve --mcp on instead (docs/MCP.md).
5
+
6
+ from basal_sdk.adapters import langchain_tool, llamaindex_tool, crewai_tool
7
+ tool = langchain_tool("http://127.0.0.1:8000") # args: state, questions
8
+ triage = crewai_tool("http://127.0.0.1:8000", preset="triage") # args: state"""
9
+ import json
10
+
11
+ NAME = "basal_decide"
12
+ DESCRIPTION = ("Typed decisions about a text (state) with calibrated probabilities, one forward pass, no generated "
13
+ "text. Put every fact the decision needs in the state. questions: {name: {type: choice | noul | score | "
14
+ "multi, instructions: the question, criteria: {key: what the option means}}}.")
15
+
16
+
17
+ def decide_fn(url="http://127.0.0.1:8000", preset=None, lang=None, client=None):
18
+ """The function every adapter wraps: (state, questions=None) -> the answers as a dict (JSON-serialisable)."""
19
+ from .client import Basal
20
+ b = client or Basal(url)
21
+
22
+ def basal_decide(state: str, questions: dict | None = None) -> dict:
23
+ if isinstance(questions, str): # agents often pass JSON text
24
+ questions = json.loads(questions)
25
+ if preset:
26
+ return b.preset(state, preset, lang)
27
+ if not questions:
28
+ raise ValueError("questions are needed (or create the tool with a preset)")
29
+ return b.decide(state, questions)
30
+ return basal_decide
31
+
32
+
33
+ def _describe(preset):
34
+ return f"{DESCRIPTION} This tool asks the '{preset}' preset: pass the state only." if preset else DESCRIPTION
35
+
36
+
37
+ def _need(module, extra):
38
+ raise ImportError(f"this adapter needs {module}: uv pip install {extra}")
39
+
40
+
41
+ def langchain_tool(url="http://127.0.0.1:8000", preset=None, lang=None, client=None):
42
+ """A LangChain StructuredTool (langchain-core)."""
43
+ try:
44
+ from langchain_core.tools import StructuredTool
45
+ except ImportError:
46
+ _need("langchain-core", "langchain-core")
47
+ return StructuredTool.from_function(func=decide_fn(url, preset, lang, client), name=NAME,
48
+ description=_describe(preset))
49
+
50
+
51
+ def llamaindex_tool(url="http://127.0.0.1:8000", preset=None, lang=None, client=None):
52
+ """A LlamaIndex FunctionTool (llama-index-core)."""
53
+ try:
54
+ from llama_index.core.tools import FunctionTool
55
+ except ImportError:
56
+ _need("llama-index-core", "llama-index-core")
57
+ return FunctionTool.from_defaults(fn=decide_fn(url, preset, lang, client), name=NAME,
58
+ description=_describe(preset))
59
+
60
+
61
+ def crewai_tool(url="http://127.0.0.1:8000", preset=None, lang=None, client=None):
62
+ """A CrewAI BaseTool."""
63
+ try:
64
+ from crewai.tools import BaseTool
65
+ except ImportError:
66
+ _need("crewai", "crewai")
67
+ fn = decide_fn(url, preset, lang, client)
68
+
69
+ class BasalDecide(BaseTool):
70
+ name: str = NAME
71
+ description: str = _describe(preset)
72
+
73
+ def _run(self, state: str, questions: dict | None = None) -> str:
74
+ return json.dumps(fn(state, questions), ensure_ascii=False)
75
+ return BasalDecide()
basal_sdk/client.py ADDED
@@ -0,0 +1,790 @@
1
+ """Python client of basal-serve: every question and task type, blocking (Basal) or asyncio (AsyncBasal). It is the
2
+ basal-sdk distribution (httpx only); with basal-engine installed, basal.client is this same module.
3
+
4
+ from basal_sdk import Basal, choice, yes_no
5
+ b = Basal("http://127.0.0.1:8000")
6
+ b.choice(state, "Which department should handle this?", {"billing": "Billing", "tech": "Technical support"})
7
+ b.decide(state, {"dept": choice("Which department?", {"billing": "Billing", "tech": "Technical support"}),
8
+ "urgent": yes_no("Is it urgent?")}) # several questions over one state: one request (SOAM)
9
+
10
+ async with AsyncBasal("http://127.0.0.1:8000") as b:
11
+ a = await b.yes_no(state, "Is it urgent?")
12
+
13
+ A method returns the answer of its question (API.md, "Response"); decide returns the answers by name, request the whole
14
+ response (with "usage"). Keyword options of a method go into the question ("option_keys", "max_error", "rank", ...);
15
+ request fields ("facts", "lang", "think", "media", ...) are client defaults or keywords of decide.
16
+
17
+ Errors follow the server's status codes, all a BasalError (a RuntimeError) with .status: InvalidRequest (422, change the
18
+ request), OutOfMemory (503, the GPU ran out of memory), NotReady (an OutOfMemory: a 503 of a server still starting or
19
+ with --max-requests in flight, or of a router with no replica ready), AuthError (a ServerError: 401 / 403, a missing,
20
+ wrong or not permitted API key) and ServerError (500 and any other status). The message is the server's error text (an
21
+ OpenAI-style error: "<type>: <message>"). No answer at all (a timeout, a connection refused or closed before the reply)
22
+ raises httpx's error, as before.
23
+
24
+ Timeouts, retries and fail-open: `timeout` (seconds, default 60) is what each attempt of a call may take in all,
25
+ from connecting to the reply's last byte (httpx.ReadTimeout past it), as in the TypeScript client, and every method
26
+ takes its own `timeout=` for that call; an httpx.Timeout instead keeps httpx's limits per connect, read and write.
27
+ `retries` (default 0) retries a call that failed in a way a later
28
+ attempt may get past (`retryable`: HTTP 429, 502, 503 or 504, a timeout, a connection refused or closed before the
29
+ reply); the n-th retry waits backoff x 2^(n-1) seconds, at random between half and all of it, plus the server's
30
+ Retry-After when it sends one (basal-serve does with 503 OVERLOADED and while it starts). `fail_open` (off by default)
31
+ answers instead of raising: fail_open(error, questions) is called once the retries are spent and returns the answers
32
+ by question name (a question it leaves out answers None, as a skipped one); it is called for failures of the server
33
+ or the connection (HTTP 429 and 5xx, a reply without answers, a timeout, no connection), while a request the server
34
+ refuses as it is (422, 401 / 403 and other 4xx) still raises. It applies to decide and the methods built on it;
35
+ request, models, capabilities and health raise.
36
+
37
+ What basal 3.0 servers add, per call (capabilities() says whether a server takes them): `trace=True` (every method)
38
+ gives each answer its trace, why it got that answer, under "trace" (request returns the response's own "trace" by
39
+ question name, a question skipped by ask_if included); `errors="per_question"` (every method) answers a question the
40
+ server cannot answer with a QuestionError in its place, a dict {"error", "code"}, while the other questions are
41
+ answered (without it one invalid question fails the call with InvalidRequest); `files=[...]` (decide and request)
42
+ sends images and audio as multipart/form-data parts instead of base64 inside the JSON: paths, bytes, binary file
43
+ objects or (one of them, content type), read once before the first attempt, so a retry sends the same bytes.
44
+
45
+ Decision rules (basal 3.0 servers, experimental): a yes_no or score question with decision_rule="<rule id>" (a rule
46
+ of the server's --decision-rules file, or BUILTIN_RULE, which needs none) gets a "decision" in its answer: a Decision,
47
+ whose .key is what the rule decided (decision_of(answer) reads it, None without one). decision() asks one such question
48
+ and returns its Decision. A refused rule raises InvalidRequest (or answers a QuestionError) with .decision_rules_code.
49
+
50
+ It also talks to other servers of the same /v1/systemone request shape, such as vLLM's structured-diffusion example
51
+ (examples/features/structured_diffusion): `api_key` sends "Authorization: Bearer <key>", choice criteria given as a
52
+ list of keys are sent as {key: null} (what basal-serve reads a list as), and a noul answer that carries only "noul"
53
+ gets "probabilities" and "confidence" from it, as basal-serve computes them. The confidences of another server are
54
+ not calibrated by basal: basal's certified thresholds (max_error) do not apply to them.
55
+ """
56
+ import asyncio
57
+ import contextvars
58
+ import datetime
59
+ import email.utils
60
+ import inspect
61
+ import json
62
+ import math
63
+ import mimetypes
64
+ import os
65
+ import random
66
+ import threading
67
+ import time
68
+
69
+ import httpx
70
+
71
+ RETRIED_STATUS = frozenset((429, 502, 503, 504)) # too many requests, a gateway without its server, unavailable, too late
72
+ RETRIED_ERRORS = (httpx.TimeoutException, httpx.NetworkError, httpx.RemoteProtocolError) # a timeout, no connection, or
73
+ # one closed before the reply
74
+ MAX_WAIT = 60.0 # seconds: the longest wait before a retry; a longer Retry-After ends the retries
75
+
76
+
77
+ def complete(answer):
78
+ """A noul answer with only "noul" (p of true) -> also "probabilities" {"true", "false"} and "confidence"; every
79
+ other answer (basal-serve's, or null for a question another server skipped) as it is."""
80
+ if isinstance(answer, dict) and answer.get("type") == "noul" and "probabilities" not in answer:
81
+ p = float(answer["noul"])
82
+ answer = dict(answer, probabilities={"true": p, "false": 1.0 - p}, confidence=max(p, 1.0 - p))
83
+ return answer
84
+
85
+
86
+ class QuestionError(dict):
87
+ """errors="per_question": the answer of a question the server could not answer, {"error": "<the message of the 422
88
+ it would have failed the request with>", "code": "INVALID_REQUEST"}, returned in its place, not raised. A dict, as
89
+ every answer (with trace=True also its "trace"); .message and .code read it."""
90
+
91
+ @property
92
+ def message(self):
93
+ return self.get("error")
94
+
95
+ @property
96
+ def code(self):
97
+ return self.get("code")
98
+
99
+ @property
100
+ def decision_rules_code(self):
101
+ """Why the question's decision_rule was refused (no_rules, unknown_rule, schema_mismatch, ...), else None."""
102
+ return self.get("decision_rules_code")
103
+
104
+
105
+ BUILTIN_RULE = "builtin:argmax-v1" # the decision rule every basal 3.0 server has: the most probable answer
106
+
107
+
108
+ class Decision(dict):
109
+ """An answer's "decision" (experimental): what the question's decision_rule decided on its probabilities. A dict,
110
+ as the server sent it; the properties read it. key: the decided option ("true" / "false" for yes_no, a level's key
111
+ for score), index: its position, method: threshold / argmax / round / baseline, rule_id, rules_id and
112
+ rules_sha256: the rule and its file (None for the builtin), probability: the decided option's, certification:
113
+ "map" when the calibration's certificates cover it (the most probable answer), "none" otherwise."""
114
+
115
+ key = property(lambda self: self.get("key"))
116
+ index = property(lambda self: self.get("index"))
117
+ method = property(lambda self: self.get("method"))
118
+ rule_id = property(lambda self: self.get("rule_id"))
119
+ rules_id = property(lambda self: self.get("rules_id"))
120
+ rules_sha256 = property(lambda self: self.get("rules_sha256"))
121
+ probability = property(lambda self: self.get("probability"))
122
+ certification = property(lambda self: self.get("certification"))
123
+
124
+ @property
125
+ def certified(self):
126
+ """True when the calibration's certificates (max_error) cover the decision: certification "map"."""
127
+ return self.get("certification") == "map"
128
+
129
+
130
+ def decision_of(answer):
131
+ """The Decision of an answer to a question with decision_rule, None for an answer without one (or None)."""
132
+ d = answer.get("decision") if isinstance(answer, dict) else None
133
+ return d if isinstance(d, Decision) else Decision(d) if isinstance(d, dict) else None
134
+
135
+
136
+ def _shaped(answers, reply, body):
137
+ """decide's answers: complete(a); with "errors": "per_question", an error answer as a QuestionError; an answer's
138
+ "decision" as a Decision; with "trace": true, every answer that is a dict with its trace (the reply's, by question
139
+ name) under "trace"."""
140
+ per_question = body.get("errors") == "per_question"
141
+ traces = reply.get("trace") if body.get("trace") is True else None
142
+ traces = traces if isinstance(traces, dict) else {}
143
+ out = {}
144
+ for k, a in answers.items():
145
+ a = complete(a)
146
+ if per_question and isinstance(a, dict) and "error" in a and "type" not in a:
147
+ a = QuestionError(a)
148
+ if isinstance(a, dict) and isinstance(a.get("decision"), dict):
149
+ a = type(a)(a, decision=Decision(a["decision"]))
150
+ if isinstance(a, dict) and k in traces:
151
+ a = type(a)(a, trace=traces[k])
152
+ out[k] = a
153
+ return out
154
+
155
+
156
+ # Media as files (3.0): the content type of a file from its name, else from its first bytes (the formats basal-serve
157
+ # decodes: Pillow's images, soundfile's audio)
158
+ SIGNATURES = ((0, b"\x89PNG\r\n\x1a\n", "image/png"), (0, b"\xff\xd8\xff", "image/jpeg"), (0, b"GIF8", "image/gif"),
159
+ (8, b"WEBP", "image/webp"), (0, b"BM", "image/bmp"), (0, b"II*\x00", "image/tiff"),
160
+ (0, b"MM\x00*", "image/tiff"), (8, b"WAVE", "audio/wav"), (0, b"fLaC", "audio/flac"),
161
+ (0, b"OggS", "audio/ogg"), (0, b"ID3", "audio/mpeg"), (0, b"\xff\xfb", "audio/mpeg"),
162
+ (0, b"\xff\xf3", "audio/mpeg"), (0, b"\xff\xf2", "audio/mpeg"))
163
+
164
+
165
+ def media_type(name, data):
166
+ """The content type of a media file: image/... or audio/... from its file name, else from its first bytes (PNG,
167
+ JPEG, GIF, WebP, BMP, TIFF, WAV, FLAC, Ogg, MP3); None when neither tells."""
168
+ guess = mimetypes.guess_type(name)[0] if name else None
169
+ if guess and guess.split("/")[0] in ("image", "audio"):
170
+ return guess
171
+ for at, magic, ctype in SIGNATURES:
172
+ if data[at:at + len(magic)] == magic and (at != 8 or data[:4] == b"RIFF"):
173
+ return ctype
174
+ return None
175
+
176
+
177
+ def _media_part(n, item):
178
+ """files[n] -> the multipart part ("media", (file name, bytes, content type)), the file read now."""
179
+ ctype = None
180
+ if isinstance(item, tuple):
181
+ if len(item) != 2:
182
+ raise TypeError(f"files[{n}]: a tuple is (file, content type), not {len(item)} items")
183
+ item, ctype = item
184
+ name = None
185
+ if isinstance(item, (str, os.PathLike)):
186
+ name = os.path.basename(os.fspath(item))
187
+ with open(item, "rb") as f:
188
+ data = f.read()
189
+ elif isinstance(item, (bytes, bytearray, memoryview)):
190
+ data = bytes(item)
191
+ elif callable(getattr(item, "read", None)):
192
+ data = item.read()
193
+ if not isinstance(data, bytes):
194
+ raise TypeError(f"files[{n}]: a file opened in binary mode ('rb'), not {type(data).__name__}")
195
+ given = getattr(item, "name", None)
196
+ name = os.path.basename(given) if isinstance(given, str) else None
197
+ else:
198
+ raise TypeError(f"files[{n}]: a path, bytes, a binary file or (one of them, content type), not "
199
+ f"{type(item).__name__}")
200
+ ctype = ctype or media_type(name, data)
201
+ if not ctype:
202
+ raise ValueError(f"files[{n}]: its type is not known from its name or bytes; give it as (file, \"image/png\")")
203
+ return "media", (name or f"media{n}", data, ctype)
204
+
205
+
206
+ def _multipart(body, files):
207
+ """The httpx keywords of a request: json=body, or with files multipart/form-data (the "request" part, the body as
208
+ httpx encodes JSON, then one "media" part per file)."""
209
+ if not files:
210
+ return {"json": body}
211
+ if not isinstance(files, list):
212
+ raise TypeError(f"files must be a list of files, not {type(files).__name__}")
213
+ request = json.dumps(body, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode()
214
+ return {"files": [("request", (None, request, "application/json"))] + [_media_part(n, f) for n, f in enumerate(files)]}
215
+
216
+
217
+ class BasalError(RuntimeError):
218
+ """A failed request: .status, the HTTP status; .retry_after, the seconds of the reply's Retry-After (None without
219
+ one)."""
220
+
221
+ def __init__(self, status, message, retry_after=None, decision_rules_code=None):
222
+ super().__init__(message)
223
+ self.status = status
224
+ self.retry_after = retry_after
225
+ self.decision_rules_code = decision_rules_code # (a 422 refusing a question's decision_rule: why)
226
+
227
+ @property
228
+ def retryable(self):
229
+ """True for HTTP 429, 502, 503 and 504: a later attempt may succeed (what `retries` retries)."""
230
+ return self.status in RETRIED_STATUS
231
+
232
+
233
+ class InvalidRequest(BasalError):
234
+ """422: the request is invalid and must be changed."""
235
+
236
+
237
+ class OutOfMemory(BasalError):
238
+ """503: the GPU ran out of memory; the same request may succeed later or on another server."""
239
+
240
+
241
+ class ServerError(BasalError):
242
+ """500 or any other status."""
243
+
244
+
245
+ class AuthError(ServerError):
246
+ """401 / 403: the API key is missing, wrong, or not allowed this route (a ServerError, as these were before)."""
247
+
248
+
249
+ class NotReady(OutOfMemory):
250
+ """503 from a server still loading its model ({"status": "starting"}) or with --max-requests in flight (code
251
+ OVERLOADED), or a router with no replica ready: the same request succeeds later. An OutOfMemory, as it was before,
252
+ and retried the same way."""
253
+
254
+
255
+ def retryable(e):
256
+ """True for a failure a later attempt of the same request may get past, which `retries` retries: a BasalError of
257
+ HTTP 429, 502, 503 or 504, or httpx's timeout or connection error (refused, or closed before the reply)."""
258
+ return isinstance(e, BasalError) and e.retryable or isinstance(e, RETRIED_ERRORS)
259
+
260
+
261
+ def fails_open(e):
262
+ """True for a failure `fail_open` answers: the server's or the connection's (HTTP 429 and 5xx, a reply that is not
263
+ JSON or has no answers, a timeout, no connection). A request the server refuses as it is (422, 401 / 403 and any
264
+ other 4xx) must change, so it still raises."""
265
+ if isinstance(e, BasalError):
266
+ return not 400 <= e.status < 500 or e.status == 429
267
+ return isinstance(e, RETRIED_ERRORS)
268
+
269
+
270
+ def _retry_after(r):
271
+ """The reply's Retry-After in seconds (a number of seconds or an HTTP date; never below 0), None without a valid
272
+ one."""
273
+ v = r.headers.get("retry-after", "").strip()
274
+ if not v:
275
+ return None
276
+ try:
277
+ s = float(v)
278
+ except ValueError:
279
+ try:
280
+ d = email.utils.parsedate_to_datetime(v)
281
+ except (TypeError, ValueError, IndexError):
282
+ return None
283
+ if d.tzinfo is None: # a date without a zone ("-0000") is UTC, as HTTP dates are
284
+ d = d.replace(tzinfo=datetime.timezone.utc)
285
+ s = d.timestamp() - time.time()
286
+ return max(0.0, s) if math.isfinite(s) else None
287
+
288
+
289
+ def _wait(attempt, backoff, retry_after=None):
290
+ """Seconds to wait after failed attempt `attempt` (0: the first): backoff x 2^attempt, at random between half and
291
+ all of it (clients that failed together do not come back together), plus the server's Retry-After; None (no
292
+ retry) when the Retry-After is longer than MAX_WAIT."""
293
+ if retry_after is not None and retry_after > MAX_WAIT:
294
+ return None
295
+ step = min(backoff * 2.0 ** min(attempt, 64), MAX_WAIT)
296
+ return (retry_after or 0.0) + random.uniform(step / 2, step)
297
+
298
+
299
+ def _pause(seconds):
300
+ time.sleep(seconds)
301
+
302
+
303
+ async def _apause(seconds):
304
+ await asyncio.sleep(seconds)
305
+
306
+
307
+ def _timeout(timeout):
308
+ """A call's own timeout for httpx: seconds > 0 or an httpx.Timeout."""
309
+ if isinstance(timeout, httpx.Timeout):
310
+ return timeout
311
+ if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or not 0 < timeout < math.inf:
312
+ raise ValueError(f"timeout must be a number of seconds > 0, not {timeout!r}")
313
+ return timeout
314
+
315
+
316
+ def _deadline(timeout):
317
+ """The seconds an attempt may take in all (connecting, sending, the reply's headers and body), or None. httpx's
318
+ own timeouts bound each connect, read and write only, so a reply sent a byte at a time held a call for as long as
319
+ the server liked; a number is also the whole attempt's limit, as in the TypeScript client. An httpx.Timeout
320
+ keeps httpx's limits per operation, and None has no limit."""
321
+ return timeout if isinstance(timeout, (int, float)) and not isinstance(timeout, bool) else None
322
+
323
+
324
+ def _late(seconds, request):
325
+ return httpx.ReadTimeout(f"no answer in {seconds:g} s (timeout)", request=request)
326
+
327
+
328
+ def _within(seconds, http, request):
329
+ """http.send(request) within seconds of elapsed time, else httpx.ReadTimeout at exactly that time. The attempt runs
330
+ in a daemon thread with the caller's context variables (tracing) and reads the reply as it comes, checking the
331
+ deadline at every chunk: past it, the thread closes the reply, so its connection is closed rather than held for a
332
+ body nobody reads, and ends. Before the reply's headers, or when the server sends nothing more, httpx's own
333
+ timeouts (the same seconds per read) end it."""
334
+ deadline = time.monotonic() + seconds
335
+ done, box, ctx = threading.Event(), [], contextvars.copy_context()
336
+
337
+ def attempt():
338
+ r = http.send(request, stream=True)
339
+ if r.is_stream_consumed: # (a transport that answers with a reply already in memory: httpx.MockTransport)
340
+ return r
341
+ try:
342
+ raw = []
343
+ for chunk in r.iter_raw():
344
+ if time.monotonic() > deadline:
345
+ return None # (the caller has its ReadTimeout already)
346
+ raw.append(chunk)
347
+ # (the bytes as sent: Content-Encoding is decoded as httpx decodes a reply it reads itself)
348
+ return httpx.Response(r.status_code, headers=r.headers, content=b"".join(raw), request=request)
349
+ finally:
350
+ r.close()
351
+
352
+ def run():
353
+ try:
354
+ box.append((True, ctx.run(attempt)))
355
+ except BaseException as e: # (raised in the caller's thread)
356
+ box.append((False, e))
357
+ finally:
358
+ done.set()
359
+ threading.Thread(target=run, name="basal-attempt", daemon=True).start()
360
+ if not done.wait(max(0.0, deadline - time.monotonic())):
361
+ raise _late(seconds, request)
362
+ ok, value = box[0]
363
+ if not ok:
364
+ raise value
365
+ if value is None: # (the attempt saw its deadline pass as the caller's wait ended)
366
+ raise _late(seconds, request)
367
+ return value
368
+
369
+
370
+ def _fail_open_of(f):
371
+ if f is not None and f is not False and not callable(f):
372
+ raise TypeError(f"fail_open must be a function (error, questions) -> answers, None or False, not {f!r}")
373
+ return f
374
+
375
+
376
+ def _opened(e, questions, answers):
377
+ """The answers fail_open returned, by question name; a question it leaves out answers None."""
378
+ if not isinstance(answers, dict):
379
+ raise TypeError(f"fail_open must return the answers by question name, not {type(answers).__name__}") from e
380
+ return {**dict.fromkeys(questions), **answers}
381
+
382
+
383
+ def _error(r):
384
+ try:
385
+ data = r.json()
386
+ except ValueError:
387
+ data = None
388
+ err = data.get("error") if isinstance(data, dict) else None
389
+ if isinstance(err, dict): # OpenAI-style: {"error": {"message", "type", ...}}
390
+ message = err.get("message") or r.text
391
+ message = f"{err['type']}: {message}" if err.get("type") else message
392
+ else:
393
+ message = r.text if err is None else err
394
+ starting = isinstance(data, dict) and (data.get("status") == "starting" or data.get("code") == "OVERLOADED") or (
395
+ isinstance(err, str) and "no basal replica is ready" in err)
396
+ if r.status_code in (401, 403):
397
+ cls = AuthError
398
+ elif r.status_code == 503:
399
+ cls = NotReady if starting else OutOfMemory
400
+ else:
401
+ cls = {422: InvalidRequest}.get(r.status_code, ServerError)
402
+ why = data.get("decision_rules_code") if isinstance(data, dict) else None
403
+ if why is None and isinstance(err, dict):
404
+ why = err.get("decision_rules_code")
405
+ return cls(r.status_code, message, _retry_after(r), why if isinstance(why, str) else None)
406
+
407
+
408
+ def _json(r):
409
+ """The JSON of a 200 reply; a body that is not JSON (a proxy's HTML page) is a ServerError, as every other failure."""
410
+ try:
411
+ return r.json()
412
+ except ValueError:
413
+ raise ServerError(r.status_code, f"the reply is not JSON: {r.text[:200]!r}") from None
414
+
415
+
416
+ def _answers(reply):
417
+ answers = reply.get("answers") if isinstance(reply, dict) else None
418
+ if not isinstance(answers, dict):
419
+ raise ServerError(200, f"the reply has no answers: {str(reply)[:200]!r}")
420
+ return answers
421
+
422
+
423
+ # Questions, for decide with several of them; the keyword options are the question's own fields (API.md, TASKS.md).
424
+
425
+ def choice(question, criteria, **opts):
426
+ """criteria: {key: description} or a list of keys."""
427
+ if isinstance(criteria, list) and all(isinstance(k, str) for k in criteria):
428
+ criteria = dict.fromkeys(criteria) # basal-serve reads a list of keys so; other servers need the map
429
+ return {"type": "choice", "instructions": question, "criteria": criteria, **opts}
430
+
431
+
432
+ def yes_no(question, true=None, false=None, **opts):
433
+ """true / false: optional descriptions of the two sides."""
434
+ crit = {k: v for k, v in (("true", true), ("false", false)) if v}
435
+ return {"type": "noul", "instructions": question, **({"criteria": crit} if crit else {}), **opts}
436
+
437
+
438
+ def score(question, levels, **opts):
439
+ """levels: lowest first."""
440
+ return {"type": "score", "instructions": question, "criteria": levels, **opts}
441
+
442
+
443
+ def multi(question, labels, **opts):
444
+ """labels: {key: description} or a list; opts: threshold, min, max, objective, exclusive, fallback, ..."""
445
+ return {"type": "multi", "instructions": question, "criteria": labels, **opts}
446
+
447
+
448
+ def act(question, outcomes, costs, **opts):
449
+ """outcomes: as choice's criteria ({"true": ..., "false": ...} for a yes/no question); costs: {action: {outcome:
450
+ cost}} or {"wrong": c, "defer": c}; opts: max_error, defer_action."""
451
+ return {"type": "act", "instructions": question, "criteria": outcomes, "costs": costs, **opts}
452
+
453
+
454
+ def tool(tools, question=None, **opts):
455
+ """tools: OpenAI, MCP or Anthropic tool definitions; opts: extra, rank, max_error, multi, description_chars."""
456
+ return {"type": "tool", "tools": tools, **({"instructions": question} if question else {}), **opts}
457
+
458
+
459
+ def rank(question, candidates, **opts):
460
+ """question: names the candidate with {candidate}; candidates: {key: text}, [text] or [{"key", "text", "group"}],
461
+ up to the server's --rank-max-candidates (10,000) per request; opts: top, chunk, label, list_title, choice_instructions, choice_context, order, prior, limit
462
+ (basal-serve's rank, experimental). A large ranking takes many engine calls: give the client a timeout to match."""
463
+ return {"type": "rank", "instructions": question, "candidates": candidates, **opts}
464
+
465
+
466
+ def classify(labels, **opts):
467
+ """labels: {name: rubric}, a list of names or of {"name", "rubric"}; opts: none, multi_label, ..."""
468
+ return {"type": "classify", "labels": labels, **opts}
469
+
470
+
471
+ def verify(claims, **opts):
472
+ """claims: {key: statement} or a list; opts: binary."""
473
+ return {"type": "verify", "claims": claims, **opts}
474
+
475
+
476
+ def compress(question=None, **opts):
477
+ """opts: unit, keep_ratio, threshold."""
478
+ return {"type": "compress", **({"instructions": question} if question else {}), **opts}
479
+
480
+
481
+ def extract(schema, **opts):
482
+ """schema: a JSON schema of the fields to copy from the state."""
483
+ return {"type": "extract", "schema": schema, **opts}
484
+
485
+
486
+ class _Client:
487
+ """What Basal and AsyncBasal share: the request body and one method per question type (in AsyncBasal each
488
+ returns a coroutine)."""
489
+
490
+ def __init__(self, url, early_exit, facts, lang, retries, backoff, fail_open):
491
+ self.base = url.rstrip("/")
492
+ self.url = self.base + "/v1/systemone"
493
+ self.defaults = {k: v for k, v in (("early_exit", early_exit), ("facts", facts), ("lang", lang)) if v}
494
+ if isinstance(retries, bool) or not isinstance(retries, int) or retries < 0:
495
+ raise ValueError(f"retries must be an integer >= 0, not {retries!r}")
496
+ if isinstance(backoff, bool) or not isinstance(backoff, (int, float)) or not 0 <= backoff < math.inf:
497
+ raise ValueError(f"backoff must be a number of seconds >= 0, not {backoff!r}")
498
+ self.retries, self.backoff = retries, backoff
499
+ self.fail_open = _fail_open_of(fail_open) or None
500
+
501
+ def _body(self, state, questions, fields):
502
+ return {"state": state, "questions": questions, **self.defaults,
503
+ **{k: v for k, v in fields.items() if v is not None}}
504
+
505
+ def _call(self, kw, timeout):
506
+ """The keywords of one HTTP request: the API key, and the call's own timeout (else the http client's)."""
507
+ if self.auth:
508
+ kw["headers"] = {**self.auth, **kw.get("headers", {})}
509
+ if timeout is not None:
510
+ kw["timeout"] = _timeout(timeout)
511
+ return kw
512
+
513
+ def _retry(self, e, attempt):
514
+ """The seconds to wait before another attempt after error e of attempt `attempt`, or None: e is raised."""
515
+ if attempt >= self.retries or not retryable(e):
516
+ return None
517
+ return _wait(attempt, self.backoff, getattr(e, "retry_after", None))
518
+
519
+ def _opener(self, e, fail_open):
520
+ """The fail_open that answers error e of a decision call (the call's own, else the client's), or None."""
521
+ f = self.fail_open if _fail_open_of(fail_open) is None else fail_open
522
+ return f if f and fails_open(e) else None
523
+
524
+ # each method: its question's own keyword options (**opts); timeout and fail_open (the module's docstring); trace
525
+ # (True: the answer's trace under "trace") and errors ("per_question": an invalid question answers a QuestionError)
526
+
527
+ def choice(self, state, question, criteria, *, timeout=None, fail_open=None, trace=None, errors=None, **opts):
528
+ return self._one(state, choice(question, criteria, **opts), timeout, fail_open, trace, errors)
529
+
530
+ def yes_no(self, state, question, true=None, false=None, *, timeout=None, fail_open=None, trace=None, errors=None,
531
+ **opts):
532
+ return self._one(state, yes_no(question, true, false, **opts), timeout, fail_open, trace, errors)
533
+
534
+ def score(self, state, question, levels, *, timeout=None, fail_open=None, trace=None, errors=None, **opts):
535
+ return self._one(state, score(question, levels, **opts), timeout, fail_open, trace, errors)
536
+
537
+ def multi(self, state, question, labels, *, timeout=None, fail_open=None, trace=None, errors=None, **opts):
538
+ return self._one(state, multi(question, labels, **opts), timeout, fail_open, trace, errors)
539
+
540
+ def act(self, state, question, outcomes, costs, *, timeout=None, fail_open=None, trace=None, errors=None, **opts):
541
+ return self._one(state, act(question, outcomes, costs, **opts), timeout, fail_open, trace, errors)
542
+
543
+ def tool(self, state, tools, question=None, *, timeout=None, fail_open=None, trace=None, errors=None, **opts):
544
+ return self._one(state, tool(tools, question, **opts), timeout, fail_open, trace, errors)
545
+
546
+ def rank(self, state, question, candidates, *, timeout=None, fail_open=None, trace=None, errors=None, **opts):
547
+ return self._one(state, rank(question, candidates, **opts), timeout, fail_open, trace, errors)
548
+
549
+ def classify(self, state, labels, *, timeout=None, fail_open=None, trace=None, errors=None, **opts):
550
+ return self._one(state, classify(labels, **opts), timeout, fail_open, trace, errors)
551
+
552
+ def verify(self, state, claims, *, timeout=None, fail_open=None, trace=None, errors=None, **opts):
553
+ return self._one(state, verify(claims, **opts), timeout, fail_open, trace, errors)
554
+
555
+ def compress(self, state, question=None, *, timeout=None, fail_open=None, trace=None, errors=None, **opts):
556
+ return self._one(state, compress(question, **opts), timeout, fail_open, trace, errors)
557
+
558
+ def extract(self, state, schema, *, timeout=None, fail_open=None, trace=None, errors=None, **opts):
559
+ return self._one(state, extract(schema, **opts), timeout, fail_open, trace, errors)
560
+
561
+ @staticmethod
562
+ def _ruled(question, rule):
563
+ """decision()'s question: a yes_no or score question (a dict) with its decision_rule."""
564
+ if not isinstance(question, dict) or question.get("type") not in ("noul", "score"):
565
+ raise ValueError("decision() takes a yes_no(...) or score(...) question")
566
+ if not isinstance(rule, str) or not rule:
567
+ raise ValueError(f"rule must be a decision rule's id, not {rule!r}")
568
+ return dict(question, decision_rule=rule)
569
+
570
+ @staticmethod
571
+ def _decision(answer):
572
+ """decision()'s result: the answer's Decision. A QuestionError (errors="per_question") is raised as the
573
+ InvalidRequest it stands for, with its decision_rules_code; an answer without a decision is a ServerError (a
574
+ server that does not know decision rules ignores the field)."""
575
+ if isinstance(answer, QuestionError):
576
+ raise InvalidRequest(422, answer.message or "the question was refused",
577
+ decision_rules_code=answer.decision_rules_code)
578
+ d = decision_of(answer)
579
+ if d is None:
580
+ raise ServerError(200, "the answer has no decision: the server does not apply decision rules (basal 3.0)")
581
+ return d
582
+
583
+
584
+ class Basal(_Client):
585
+ """A blocking client. http: an httpx.Client of your own (headers, transport, proxies); timeout and transport apply
586
+ otherwise. api_key: sent as "Authorization: Bearer <key>". timeout, retries, backoff and fail_open: the module's
587
+ docstring."""
588
+
589
+ def __init__(self, url="http://127.0.0.1:8000", timeout=60, early_exit=None, facts=None, lang=None, retries=0,
590
+ backoff=0.5, http=None, transport=None, api_key=None, fail_open=None):
591
+ super().__init__(url, early_exit, facts, lang, retries, backoff, fail_open)
592
+ self.http = http or httpx.Client(timeout=timeout, transport=transport)
593
+ self.timeout = None if http else _deadline(timeout) # (an http client of your own: its timeouts)
594
+ self.auth = {"Authorization": f"Bearer {api_key}"} if api_key else {} # per request: a shared http stays untouched
595
+
596
+ def _send(self, method, url, timeout=None, **kw):
597
+ kw = self._call(kw, timeout)
598
+ limit = self.timeout if timeout is None else _deadline(timeout)
599
+ for attempt in range(self.retries + 1):
600
+ try:
601
+ req = self.http.build_request(method, url, **kw)
602
+ r = self.http.send(req) if limit is None else _within(limit, self.http, req)
603
+ except RETRIED_ERRORS as exc:
604
+ e = exc
605
+ else:
606
+ if r.status_code == 200:
607
+ return _json(r)
608
+ e = _error(r)
609
+ wait = self._retry(e, attempt)
610
+ if wait is None:
611
+ raise e
612
+ _pause(wait)
613
+
614
+ def request(self, body, *, timeout=None, files=None):
615
+ """The whole response to a request body (answers, model, usage, and "trace" with "trace": true). files: media
616
+ sent as multipart/form-data parts (the module's docstring)."""
617
+ return self._send("POST", self.url, timeout, **_multipart(body, files))
618
+
619
+ def decide(self, state, questions, *, timeout=None, fail_open=None, files=None, **fields):
620
+ """{name: answer} for {name: question}; fields: request fields (facts, lang, think, media, trace, errors, ...).
621
+ timeout: of this call; fail_open: of this call (False: none), else the client's; files: media as files."""
622
+ body = self._body(state, questions, fields)
623
+ try: # (a file of files that cannot be read raises its own error, before any request)
624
+ reply = self.request(body, timeout=timeout, files=files)
625
+ answers = _answers(reply)
626
+ except (BasalError, httpx.TransportError) as e:
627
+ f = self._opener(e, fail_open)
628
+ if f is None:
629
+ raise
630
+ return {k: complete(a) for k, a in _opened(e, questions, f(e, questions)).items()}
631
+ return _shaped(answers, reply, body)
632
+
633
+ def _one(self, state, q, timeout=None, fail_open=None, trace=None, errors=None):
634
+ return self.decide(state, {"q": q}, timeout=timeout, fail_open=fail_open, trace=trace, errors=errors)["q"]
635
+
636
+ def decision(self, state, question, rule=BUILTIN_RULE, *, timeout=None, **fields):
637
+ """The Decision of one yes_no(...) or score(...) question under a decision rule (experimental): rule, its id in
638
+ the server's --decision-rules file, or BUILTIN_RULE. A refused rule raises InvalidRequest with
639
+ .decision_rules_code; fields: request fields (lang, facts, ...)."""
640
+ q = self._ruled(question, rule)
641
+ return self._decision(self.decide(state, {"q": q}, timeout=timeout, fail_open=False, **fields)["q"])
642
+
643
+ def preset(self, state, name, lang=None, max_error=None, *, timeout=None, fail_open=None):
644
+ """The answers to a ready question set (basal_sdk.presets: triage, moderation, compliance, guard_input,
645
+ guard_output, route_intent) about state; max_error adds the abstain flag to every answer. The wording is in
646
+ `lang`, else the client's `lang`, else the language of the state."""
647
+ from .presets import lang_of, questions
648
+ lang = lang or self.defaults.get("lang") or lang_of(state)
649
+ return self.decide(state, questions(name, lang, state, max_error), lang=lang,
650
+ timeout=timeout, fail_open=fail_open)
651
+
652
+ def guard(self, state, kind="input", policy="strict", lang=None, max_error=None, *, timeout=None, fail_open=None):
653
+ """Run the guard_input / guard_output battery on state -> presets.guard(): {"action": pass | review | block |
654
+ support, "reason", "checks"} plus "answers". max_error takes the thresholds from the model's calibration."""
655
+ from .presets import guard
656
+ answers = self.preset(state, "guard_" + kind, lang, max_error, timeout=timeout, fail_open=fail_open)
657
+ return {**guard(answers, policy, max_error, expect=kind), "answers": answers}
658
+
659
+ def route(self, state, lang=None, min_confidence=0.6, max_error=None, *, timeout=None, fail_open=None):
660
+ """Run route_intent on state -> presets.route(): the intent, or "human" on low confidence / abstain."""
661
+ from .presets import route
662
+ answers = self.preset(state, "route_intent", lang, max_error, timeout=timeout, fail_open=fail_open)
663
+ return {**route(answers, min_confidence, max_error), "answers": answers}
664
+
665
+ def models(self, *, timeout=None):
666
+ return self._send("GET", self.base + "/v1/models", timeout)["models"]
667
+
668
+ def capabilities(self, *, timeout=None):
669
+ """GET /v1/capabilities (basal 3.0 servers): what the server takes, as a dict: "version", "model", "mode",
670
+ "endpoints", "question_types", "decisions_question_types", "options" ({"min", "max"} per question), "request"
671
+ (the values each request field takes, an empty list for a field the server does not take: "facts", "lang",
672
+ "media", "detail", "early_exit", "think", "evidence", "coverage", "max_error", "trace" ([False, True]),
673
+ "errors" (["request", "per_question"]), "media_upload" (["base64", "multipart"] on a server with media, so
674
+ files= works)) and "limits" ("max_branches", "max_body_bytes", "max_prompt_bytes", "max_requests",
675
+ "request_timeout_s", "rank_max_candidates", "context_tokens", "max_depth", "decisions_max_questions",
676
+ "response_cache": {"max_bytes", "ttl_s"} or None). Through basal-router also "router": its own limits and
677
+ options, which apply first ("replicas", "ready", "max_requests", "max_requests_per_key", "max_body_bytes",
678
+ "api_keys", "replica_timeout_s", "load_factor", "prefix_affinity", "state_holders", "cascade_levels",
679
+ "blend_models", "fallback", "routes"). docs/API.md has an example."""
680
+ return self._send("GET", self.base + "/v1/capabilities", timeout)
681
+
682
+ def health(self, *, timeout=None):
683
+ return self._send("GET", self.base + "/health", timeout)
684
+
685
+ def close(self):
686
+ self.http.close()
687
+
688
+ def __enter__(self):
689
+ return self
690
+
691
+ def __exit__(self, *exc):
692
+ self.close()
693
+
694
+
695
+ class AsyncBasal(_Client):
696
+ """The asyncio client: the methods of Basal as coroutines. http: an httpx.AsyncClient of your own."""
697
+
698
+ def __init__(self, url="http://127.0.0.1:8000", timeout=60, early_exit=None, facts=None, lang=None, retries=0,
699
+ backoff=0.5, http=None, transport=None, api_key=None, fail_open=None):
700
+ super().__init__(url, early_exit, facts, lang, retries, backoff, fail_open)
701
+ self.http = http or httpx.AsyncClient(timeout=timeout, transport=transport)
702
+ self.timeout = None if http else _deadline(timeout)
703
+ self.auth = {"Authorization": f"Bearer {api_key}"} if api_key else {} # per request: a shared http stays untouched
704
+
705
+ async def _send(self, method, url, timeout=None, **kw):
706
+ kw = self._call(kw, timeout)
707
+ limit = self.timeout if timeout is None else _deadline(timeout)
708
+ for attempt in range(self.retries + 1):
709
+ try:
710
+ req = self.http.build_request(method, url, **kw)
711
+ if limit is None:
712
+ r = await self.http.send(req)
713
+ else:
714
+ try:
715
+ r = await asyncio.wait_for(self.http.send(req), limit)
716
+ except asyncio.TimeoutError:
717
+ raise _late(limit, req) from None
718
+ except RETRIED_ERRORS as exc:
719
+ e = exc
720
+ else:
721
+ if r.status_code == 200:
722
+ return _json(r)
723
+ e = _error(r)
724
+ wait = self._retry(e, attempt)
725
+ if wait is None:
726
+ raise e
727
+ await _apause(wait)
728
+
729
+ async def request(self, body, *, timeout=None, files=None):
730
+ return await self._send("POST", self.url, timeout, **_multipart(body, files))
731
+
732
+ async def decide(self, state, questions, *, timeout=None, fail_open=None, files=None, **fields):
733
+ """As Basal.decide; fail_open may be a coroutine function."""
734
+ body = self._body(state, questions, fields)
735
+ try:
736
+ reply = await self.request(body, timeout=timeout, files=files)
737
+ answers = _answers(reply)
738
+ except (BasalError, httpx.TransportError) as e:
739
+ f = self._opener(e, fail_open)
740
+ if f is None:
741
+ raise
742
+ answers = f(e, questions)
743
+ answers = _opened(e, questions, await answers if inspect.isawaitable(answers) else answers)
744
+ return {k: complete(a) for k, a in answers.items()}
745
+ return _shaped(answers, reply, body)
746
+
747
+ async def _one(self, state, q, timeout=None, fail_open=None, trace=None, errors=None):
748
+ return (await self.decide(state, {"q": q}, timeout=timeout, fail_open=fail_open, trace=trace,
749
+ errors=errors))["q"]
750
+
751
+ async def decision(self, state, question, rule=BUILTIN_RULE, *, timeout=None, **fields):
752
+ """As Basal.decision."""
753
+ q = self._ruled(question, rule)
754
+ return self._decision((await self.decide(state, {"q": q}, timeout=timeout, fail_open=False, **fields))["q"])
755
+
756
+ async def preset(self, state, name, lang=None, max_error=None, *, timeout=None, fail_open=None):
757
+ from .presets import lang_of, questions
758
+ lang = lang or self.defaults.get("lang") or lang_of(state)
759
+ return await self.decide(state, questions(name, lang, state, max_error), lang=lang,
760
+ timeout=timeout, fail_open=fail_open)
761
+
762
+ async def guard(self, state, kind="input", policy="strict", lang=None, max_error=None, *, timeout=None,
763
+ fail_open=None):
764
+ from .presets import guard
765
+ answers = await self.preset(state, "guard_" + kind, lang, max_error, timeout=timeout, fail_open=fail_open)
766
+ return {**guard(answers, policy, max_error, expect=kind), "answers": answers}
767
+
768
+ async def route(self, state, lang=None, min_confidence=0.6, max_error=None, *, timeout=None, fail_open=None):
769
+ from .presets import route
770
+ answers = await self.preset(state, "route_intent", lang, max_error, timeout=timeout, fail_open=fail_open)
771
+ return {**route(answers, min_confidence, max_error), "answers": answers}
772
+
773
+ async def models(self, *, timeout=None):
774
+ return (await self._send("GET", self.base + "/v1/models", timeout))["models"]
775
+
776
+ async def capabilities(self, *, timeout=None):
777
+ """As Basal.capabilities."""
778
+ return await self._send("GET", self.base + "/v1/capabilities", timeout)
779
+
780
+ async def health(self, *, timeout=None):
781
+ return await self._send("GET", self.base + "/health", timeout)
782
+
783
+ async def aclose(self):
784
+ await self.http.aclose()
785
+
786
+ async def __aenter__(self):
787
+ return self
788
+
789
+ async def __aexit__(self, *exc):
790
+ await self.aclose()
basal_sdk/presets.py ADDED
@@ -0,0 +1,280 @@
1
+ """Ready question sets for common jobs (2.5): `basal-run --preset triage`, `Basal.preset(state, "triage")`, the
2
+ framework adapters (basal_sdk.adapters). Each preset has Polish and English wording; the language follows the state
3
+ unless given. The questions are plain HTTP-API questions (docs/API.md), so a preset is only a starting point: copy
4
+ and edit it for your own rules.
5
+
6
+ basal-run --list-presets
7
+ basal-run --preset triage --input tickets.jsonl --output out.jsonl (input lines: {"state": "..."})
8
+
9
+ The guard_input / guard_output / route_intent presets also come with a decision step: `guard(answers, policy)` and
10
+ `route(answers)` turn the answers into pass / review / block / support or an intent route (docs/SERVING.md)."""
11
+ import copy
12
+ import math
13
+ import re
14
+
15
+ LEVELS = {"pl": ["niska", "średnia", "wysoka"], "en": ["low", "medium", "high"]} # score levels, lowest first
16
+ SEVERITY = {"pl": ["brak", "niska", "umiarkowana", "poważna"], "en": ["none", "low", "moderate", "severe"]} # 0-3
17
+ COMPLEXITY = {"pl": ["prosta", "średnia", "złożona"], "en": ["simple", "moderate", "complex"]}
18
+
19
+ PRESETS = {
20
+ "triage": {
21
+ "pl": {
22
+ "urgency": {"type": "score", "instructions": "Jak pilna jest sprawa?", "criteria": LEVELS["pl"]},
23
+ "category": {"type": "choice", "instructions": "Czego dotyczy zgłoszenie?",
24
+ "criteria": {"complaint": "reklamacja lub skarga", "billing": "płatności lub faktury",
25
+ "technical": "problem techniczny", "account": "konto lub dane klienta",
26
+ "other": "coś innego"}},
27
+ "needs_human": {"type": "noul", "instructions": "Czy sprawa wymaga decyzji człowieka?"},
28
+ },
29
+ "en": {
30
+ "urgency": {"type": "score", "instructions": "How urgent is this case?", "criteria": LEVELS["en"]},
31
+ "category": {"type": "choice", "instructions": "What is the request about?",
32
+ "criteria": {"complaint": "a complaint", "billing": "payments or invoices",
33
+ "technical": "a technical problem", "account": "the account or customer data",
34
+ "other": "something else"}},
35
+ "needs_human": {"type": "noul", "instructions": "Does the case need a human decision?"},
36
+ },
37
+ },
38
+ "moderation": {
39
+ "pl": {
40
+ "harmful": {"type": "noul", "instructions": "Czy tekst zawiera treści obraźliwe, groźby lub nękanie?"},
41
+ "spam": {"type": "noul", "instructions": "Czy tekst jest spamem lub reklamą?"},
42
+ "personal_data": {"type": "noul", "instructions": "Czy tekst ujawnia dane osobowe innej osoby?"},
43
+ },
44
+ "en": {
45
+ "harmful": {"type": "noul", "instructions": "Does the text contain insults, threats or harassment?"},
46
+ "spam": {"type": "noul", "instructions": "Is the text spam or advertising?"},
47
+ "personal_data": {"type": "noul", "instructions": "Does the text reveal someone else's personal data?"},
48
+ },
49
+ },
50
+ "compliance": {
51
+ "pl": {
52
+ "personal_data": {"type": "noul", "instructions": "Czy dokument zawiera dane osobowe?"},
53
+ "deadline": {"type": "noul", "instructions": "Czy dokument wyznacza termin do dotrzymania?"},
54
+ "legal_review": {"type": "noul", "instructions": "Czy dokument powinien przejrzeć prawnik?"},
55
+ },
56
+ "en": {
57
+ "personal_data": {"type": "noul", "instructions": "Does the document contain personal data?"},
58
+ "deadline": {"type": "noul", "instructions": "Does the document set a deadline to meet?"},
59
+ "legal_review": {"type": "noul", "instructions": "Should a lawyer review the document?"},
60
+ },
61
+ },
62
+ }
63
+
64
+ def _guard(lang, who):
65
+ """The guard battery in `lang`; who = "input" (what a user sent) or "output" (what the assistant is about to say)."""
66
+ pl = lang == "pl"
67
+ if who == "input":
68
+ first = ("jailbreak", "Czy wiadomość próbuje obejść zasady lub instrukcje asystenta (jailbreak, wstrzyknięcie polecenia)?"
69
+ if pl else "Does the message try to get around the assistant's rules or instructions (jailbreak, prompt injection)?")
70
+ harmful = ("Czy wiadomość prosi o pomoc w czymś szkodliwym lub nielegalnym (przemoc, broń, włamanie, oszustwo)?"
71
+ if pl else "Does the message ask for help with something harmful or illegal (violence, weapons, hacking, fraud)?")
72
+ medical = ("Czy wiadomość prosi o poradę medyczną, diagnozę lub dawkowanie leków?"
73
+ if pl else "Does the message ask for medical advice, a diagnosis or a medication dose?")
74
+ selfh = ("Czy autor wiadomości mówi o zrobieniu sobie krzywdy lub odebraniu sobie życia?"
75
+ if pl else "Does the author talk about hurting themselves or ending their life?")
76
+ sev = ("Jak poważne ryzyko niesie ta wiadomość?" if pl else "How serious is the risk this message carries?")
77
+ else:
78
+ first = ("policy_break", "Czy odpowiedź łamie zasady: ujawnia instrukcje systemowe, dane poufne albo wykonuje zabronione polecenie?"
79
+ if pl else "Does the reply break the rules: reveal system instructions, confidential data or follow a forbidden command?")
80
+ harmful = ("Czy odpowiedź zawiera szkodliwe lub nielegalne instrukcje (przemoc, broń, włamanie, oszustwo)?"
81
+ if pl else "Does the reply contain harmful or illegal instructions (violence, weapons, hacking, fraud)?")
82
+ medical = ("Czy odpowiedź udziela porady medycznej, diagnozy lub dawkowania leków?"
83
+ if pl else "Does the reply give medical advice, a diagnosis or a medication dose?")
84
+ selfh = ("Czy odpowiedź zawiera treści o samookaleczeniu lub samobójstwie albo je zachęca?"
85
+ if pl else "Does the reply contain content about self-harm or suicide, or encourage it?")
86
+ sev = ("Jak poważne ryzyko niesie ta odpowiedź?" if pl else "How serious is the risk this reply carries?")
87
+ return {first[0]: {"type": "noul", "instructions": first[1]},
88
+ "harmful": {"type": "noul", "instructions": harmful},
89
+ "medical": {"type": "noul", "instructions": medical},
90
+ "self_harm": {"type": "noul", "instructions": selfh},
91
+ "severity": {"type": "score", "instructions": sev, "criteria": SEVERITY[lang]}}
92
+
93
+
94
+ for _who in ("input", "output"):
95
+ PRESETS["guard_" + _who] = {lang: _guard(lang, _who) for lang in ("pl", "en")}
96
+
97
+ PRESETS["route_intent"] = {
98
+ "pl": {
99
+ "intent": {"type": "choice", "instructions": "Czego chce autor wiadomości?",
100
+ "criteria": {"question": "odpowiedź na pytanie o fakty lub instrukcję",
101
+ "action": "wykonanie czynności (zmiana, zamówienie, anulowanie)",
102
+ "complaint": "skarga lub reklamacja", "sales": "oferta, cennik lub zakup",
103
+ "chitchat": "luźna rozmowa", "other": "coś innego"}},
104
+ "complexity": {"type": "score", "instructions": "Jak złożona jest sprawa?", "criteria": COMPLEXITY["pl"]},
105
+ },
106
+ "en": {
107
+ "intent": {"type": "choice", "instructions": "What does the author of the message want?",
108
+ "criteria": {"question": "an answer to a factual or how-to question",
109
+ "action": "an action done (a change, an order, a cancellation)",
110
+ "complaint": "a complaint", "sales": "an offer, a price list or a purchase",
111
+ "chitchat": "casual conversation", "other": "something else"}},
112
+ "complexity": {"type": "score", "instructions": "How complex is the case?", "criteria": COMPLEXITY["en"]},
113
+ },
114
+ }
115
+
116
+ # Named policies for guard(). A yes/no hazard maps to an action when its probability reaches `act_at`, and to review
117
+ # from `review_at`; a hazard whose action is "pass" is allowed. The severity score (0-3) acts from level `block` /
118
+ # `review`. With max_error (certified mode) the thresholds come from the calibration instead: see guard().
119
+ POLICIES = {
120
+ "strict": {"act_at": 0.5, "review_at": 0.15, "severity": {"review": 1, "block": 2},
121
+ "hazards": {"jailbreak": "block", "policy_break": "block", "harmful": "block",
122
+ "medical": "review", "self_harm": "support"}},
123
+ "permissive": {"act_at": 0.85, "review_at": 0.5, "severity": {"review": 2, "block": 3},
124
+ "hazards": {"jailbreak": "block", "policy_break": "block", "harmful": "block",
125
+ "medical": "pass", "self_harm": "support"}},
126
+ }
127
+ PRECEDENCE = ["support", "block", "review", "pass"] # the strongest action of all the checks wins
128
+
129
+
130
+ # Signs of Polish: diacritics and common words, also as typed without diacritics (sie, ze, juz); the one-letter and
131
+ # short words count only in lower case (not "CO", "PO", "W", nor "w/o"). Signs of English: its common words and "I".
132
+ # Words both languages write the same way ("i", "do", "to", "on", "a", "no") count for neither.
133
+ _PL = re.compile(r"[ąćęłńóśźż]|\b(?:nie|się|sie|jest|są|że|ze|jak|czy|mnie|mam|mogę|moge|dla|przez|już|juz|ale|bo|też"
134
+ r"|tez|jestem|mój|moj|moje|moim|kiedy|dlaczego|proszę|prosze)\b|\b(?-i:w|z|na|co|od|po|mi)\b(?!/)", re.I)
135
+ _EN = re.compile(r"\b(?:the|and|is|are|of|my|it|in|for|not|this|that|with|you|your|me|can|cannot|does|please|have|has"
136
+ r"|was|be|how|why|where|what|when)\b|\b(?-i:I)\b", re.I)
137
+
138
+
139
+ def names():
140
+ return sorted(PRESETS)
141
+
142
+
143
+ def lang_of(text):
144
+ """pl when the text has more signs of Polish (diacritics, common words) than common English words, else en. A
145
+ short ticket typed without diacritics ("nie dziala logowanie") is Polish; a text with no sign of either is en."""
146
+ text = text or ""
147
+ return "pl" if len(_PL.findall(text)) > len(_EN.findall(text)) else "en"
148
+
149
+
150
+ def questions(name, lang=None, state="", max_error=None):
151
+ """The questions of preset `name` in `lang` (pl / en; None: the language of `state`), as a fresh dict. With
152
+ `max_error` every choice / noul / score question asks for the abstain flag at that error target."""
153
+ if name not in PRESETS:
154
+ raise ValueError(f"unknown preset {name!r} (presets: {', '.join(names())})")
155
+ lang = lang or lang_of(state)
156
+ if lang not in PRESETS[name]:
157
+ raise ValueError(f"preset {name!r} has no {lang!r} wording (pl, en)")
158
+ qs = copy.deepcopy(PRESETS[name][lang])
159
+ if max_error is not None:
160
+ for q in qs.values():
161
+ if q["type"] in ("choice", "noul", "score"):
162
+ q["max_error"] = max_error
163
+ return qs
164
+
165
+
166
+ def _policy(policy):
167
+ if isinstance(policy, dict):
168
+ return policy
169
+ if policy not in POLICIES:
170
+ raise ValueError(f"unknown policy {policy!r} (policies: {', '.join(sorted(POLICIES))})")
171
+ return POLICIES[policy]
172
+
173
+
174
+ def _prob(x):
175
+ """A probability as a float, None when it is not a finite number in [0, 1] (a bool, null, NaN, text)."""
176
+ if isinstance(x, bool) or not isinstance(x, (int, float)) or not math.isfinite(x) or not 0 <= x <= 1:
177
+ return None
178
+ return float(x)
179
+
180
+
181
+ def _level(ans):
182
+ """The most probable level of a score answer (0 = the first), None when its probabilities are not a non-empty
183
+ {level index: probability} map."""
184
+ probs = ans.get("probabilities")
185
+ if not isinstance(probs, dict) or not probs:
186
+ return None
187
+ if any(_prob(v) is None or not str(k).isdigit() for k, v in probs.items()):
188
+ return None
189
+ return int(max(probs, key=probs.get))
190
+
191
+
192
+ def battery(kind):
193
+ """The question names of the guard_input ("input") or guard_output ("output") battery."""
194
+ if kind not in ("input", "output"):
195
+ raise ValueError(f"unknown battery {kind!r} (input, output, or a list of question names)")
196
+ return list(PRESETS["guard_" + kind]["en"])
197
+
198
+
199
+ def guard(answers, policy="strict", max_error=None, expect=None):
200
+ """Answers of a guard_input / guard_output battery -> {"action": pass | review | block | support, "reason", "checks"}.
201
+
202
+ Precedence (fixed): support > block > review > pass. Every question of the battery must be answered: `expect` is
203
+ "input" or "output" (the built-in batteries), a list of question names (a battery of your own, or an intentional
204
+ part of one), or None (the built-in battery of the answers: output when they hold policy_break and no jailbreak,
205
+ else input). A question of the battery that is missing or null, and an answer that is malformed (a yes/no
206
+ probability that is not a finite number in [0, 1], a severity without a {level: probability} map), is a review,
207
+ never a pass. Hand-picked mode (max_error None): see POLICIES. Certified mode (max_error=0.05; ask the questions
208
+ with the same `max_error`): a hazard is hit when its probability is 0.5 or more and acts as the policy says, and an
209
+ answer the server marks `abstain` (below the threshold certified for that error target and type, or none
210
+ certified) is a review, as is one without a true / false abstain flag. The thresholds are then those of the model's
211
+ calibration, not numbers of the policy."""
212
+ pol = _policy(policy)
213
+ if not isinstance(answers, dict):
214
+ raise ValueError("answers must be an object of question name -> answer")
215
+ if expect is None:
216
+ expect = "output" if "policy_break" in answers and "jailbreak" not in answers else "input"
217
+ names = battery(expect) if isinstance(expect, str) else [str(x) for x in expect]
218
+ checks, worst = {}, "pass"
219
+
220
+ def put(name, action, p=None, why=None):
221
+ nonlocal worst
222
+ checks[name] = {"action": action, "p": p, **({"why": why} if why else {})}
223
+ if PRECEDENCE.index(action) < PRECEDENCE.index(worst):
224
+ worst = action
225
+
226
+ for name, ans in list(answers.items()) + [(n, None) for n in names if n not in answers]:
227
+ if ans is None or not isinstance(ans, dict):
228
+ put(name, "review", None, "no answer")
229
+ continue
230
+ if max_error is not None and not isinstance(ans.get("abstain"), bool):
231
+ put(name, "review", None, "no abstain flag: ask with max_error")
232
+ continue
233
+ if name == "severity":
234
+ lvl, sev = _level(ans), pol["severity"]
235
+ if lvl is None:
236
+ put(name, "review", None, "malformed answer")
237
+ continue
238
+ act = "block" if lvl >= sev["block"] else "review" if lvl >= sev["review"] else "pass"
239
+ if max_error is not None and ans["abstain"] and act == "pass":
240
+ act = "review"
241
+ put(name, act, float(lvl))
242
+ continue
243
+ p = _prob(ans.get("noul"))
244
+ if p is None:
245
+ put(name, "review", None, "malformed answer")
246
+ continue
247
+ hazard = pol["hazards"].get(name)
248
+ if hazard is None or hazard == "pass":
249
+ put(name, "pass", p)
250
+ continue
251
+ if max_error is not None:
252
+ act = "review" if ans["abstain"] else hazard if p >= 0.5 else "pass"
253
+ else:
254
+ act = hazard if p >= pol["act_at"] else "review" if p >= pol["review_at"] else "pass"
255
+ put(name, act, p)
256
+ reason = next((n for n, c in checks.items() if c["action"] == worst), None) if worst != "pass" else None
257
+ return {"action": worst, "reason": reason, "checks": checks, "mode": "certified" if max_error is not None else "fixed"}
258
+
259
+
260
+ def route(answers, min_confidence=0.6, max_error=None):
261
+ """Answers of route_intent -> {"route": <intent> | "human", "complexity": <level name>, "level": int}. Low confidence
262
+ (below `min_confidence`), an abstain (with max_error; an answer without a true / false abstain flag too), a missing
263
+ or a malformed answer (a confidence that is not a finite number in [0, 1], complexity without a {level:
264
+ probability} map) routes to a human."""
265
+ intent, comp = answers.get("intent"), answers.get("complexity")
266
+ if not intent or not comp or not isinstance(intent, dict) or not isinstance(comp, dict):
267
+ return {"route": "human", "why": "no answer"}
268
+ lvl, conf = _level(comp), _prob(intent.get("confidence"))
269
+ if lvl is None or conf is None or not isinstance(intent.get("choice"), str):
270
+ return {"route": "human", "why": "malformed answer"}
271
+ legend = comp.get("legend") or {}
272
+ out = {"route": intent["choice"], "complexity": legend.get(str(lvl)), "level": lvl, "confidence": conf}
273
+ if max_error is not None:
274
+ if not isinstance(intent.get("abstain"), bool) or not isinstance(comp.get("abstain"), bool):
275
+ return {"route": "human", "why": "no abstain flag: ask with max_error"}
276
+ if intent["abstain"] or comp["abstain"]:
277
+ return {**out, "route": "human", "why": "abstain"}
278
+ elif conf < min_confidence:
279
+ return {**out, "route": "human", "why": "low confidence"}
280
+ return out
@@ -0,0 +1,42 @@
1
+ Metadata-Version: 2.4
2
+ Name: basal-sdk
3
+ Version: 3.0.3
4
+ Summary: Python client for basal-serve: typed decisions (choice / yes-no / score) with calibrated probabilities
5
+ License-Expression: Apache-2.0
6
+ Requires-Python: >=3.10
7
+ Description-Content-Type: text/markdown
8
+ Requires-Dist: httpx>=0.28
9
+ Provides-Extra: test
10
+ Requires-Dist: pytest; extra == "test"
11
+
12
+ # basal-sdk
13
+
14
+ The Python client of [basal](https://github.com/rkinas/basal)'s server, basal-serve: typed decisions (choice, yes-no,
15
+ score and the other question types of `POST /v1/systemone`) with calibrated probabilities. Blocking (`Basal`) or
16
+ asyncio (`AsyncBasal`), with timeouts, retries and fail-open; ready question sets (`basal_sdk.presets`) and tools for
17
+ LangChain, LlamaIndex and CrewAI (`basal_sdk.adapters`). Its only dependency is httpx: no torch, no model.
18
+
19
+ ```bash
20
+ pip install basal-sdk
21
+ ```
22
+
23
+ ```python
24
+ from basal_sdk import Basal, choice, yes_no
25
+
26
+ b = Basal("http://127.0.0.1:8000", timeout=10, retries=2)
27
+ a = b.decide("Since 7:40 no card terminal works in the Gdańsk branch; only cash.",
28
+ {"dept": choice("Which department?", {"it": "IT", "tills": "Tills"}),
29
+ "card": yes_no("Is it about card payments?")})
30
+ print(a["dept"]["choice"], a["card"]["noul"])
31
+ ```
32
+
33
+ Which install gives which import:
34
+
35
+ | Install | Imports |
36
+ |---|---|
37
+ | `pip install basal-sdk` (an application that calls a server) | `basal_sdk` |
38
+ | `pip install basal-engine` (the server; it installs basal-sdk of the same version) | `basal` and `basal_sdk`; `basal.client`, `basal.presets` and `basal.adapters` are the modules of `basal_sdk` |
39
+
40
+ basal-sdk and basal-engine are released together, at one version. The methods, errors and options are described in
41
+ [docs/INSTALL.md](https://github.com/rkinas/basal/blob/main/docs/INSTALL.md#python-client) and the request and answer
42
+ shapes in [docs/API.md](https://github.com/rkinas/basal/blob/main/docs/API.md). Apache-2.0.
@@ -0,0 +1,8 @@
1
+ basal_sdk/__init__.py,sha256=Gov9JW3fIpZe6QfYihPvbYOW35A7SYPdJI-KpHpNxdQ,1554
2
+ basal_sdk/adapters.py,sha256=GJru0Xnk1aXRAyPgFR7IWj-NnG2lLys_NbHlADRrwLc,3439
3
+ basal_sdk/client.py,sha256=PZdc1ig0bd-d5HwC2gAExfAJHPiprFRugYHuIBnxgho,41543
4
+ basal_sdk/presets.py,sha256=xrxh9kE0cUWlXLnuJgidNhK5WI8PPRKq6nav9_kl7oU,16966
5
+ basal_sdk-3.0.3.dist-info/METADATA,sha256=WQWqDw9Y9sLeOykOi2-mpwvHJ13c7kCQy8GyEACaS0M,1915
6
+ basal_sdk-3.0.3.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
+ basal_sdk-3.0.3.dist-info/top_level.txt,sha256=heh589jd5eL6oHtVo88h-io7NVsJP8dSDdv1s525Lhw,10
8
+ basal_sdk-3.0.3.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ basal_sdk