noullama 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.
- noullama/__init__.py +35 -0
- noullama/answers.py +52 -0
- noullama/client.py +182 -0
- noullama/config.py +47 -0
- noullama/errors.py +52 -0
- noullama/images.py +31 -0
- noullama/py.typed +0 -0
- noullama/questions.py +104 -0
- noullama-0.2.0.dist-info/METADATA +190 -0
- noullama-0.2.0.dist-info/RECORD +13 -0
- noullama-0.2.0.dist-info/WHEEL +5 -0
- noullama-0.2.0.dist-info/licenses/LICENSE +21 -0
- noullama-0.2.0.dist-info/top_level.txt +1 -0
noullama/__init__.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
__version__ = "0.2.0"
|
|
2
|
+
|
|
3
|
+
from .answers import Answer, Decision
|
|
4
|
+
from .client import Client
|
|
5
|
+
from .errors import (
|
|
6
|
+
BadRequest,
|
|
7
|
+
AuthError,
|
|
8
|
+
Forbidden,
|
|
9
|
+
UnknownModel,
|
|
10
|
+
AmbiguousModel,
|
|
11
|
+
InferenceFailed,
|
|
12
|
+
ModelUnavailable,
|
|
13
|
+
NotRunning,
|
|
14
|
+
NoullamaError,
|
|
15
|
+
)
|
|
16
|
+
from .questions import Choice, Noul, Score
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"__version__",
|
|
20
|
+
"Answer",
|
|
21
|
+
"Choice",
|
|
22
|
+
"Client",
|
|
23
|
+
"Decision",
|
|
24
|
+
"Noul",
|
|
25
|
+
"Score",
|
|
26
|
+
"BadRequest",
|
|
27
|
+
"AuthError",
|
|
28
|
+
"Forbidden",
|
|
29
|
+
"UnknownModel",
|
|
30
|
+
"AmbiguousModel",
|
|
31
|
+
"InferenceFailed",
|
|
32
|
+
"ModelUnavailable",
|
|
33
|
+
"NotRunning",
|
|
34
|
+
"NoullamaError",
|
|
35
|
+
]
|
noullama/answers.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
from collections.abc import Iterator
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@dataclass
|
|
7
|
+
class Answer:
|
|
8
|
+
type: str
|
|
9
|
+
value: Any
|
|
10
|
+
probabilities: dict[str, float] | None
|
|
11
|
+
confidence: float | None
|
|
12
|
+
raw: dict
|
|
13
|
+
|
|
14
|
+
@classmethod
|
|
15
|
+
def from_raw(cls, raw: dict) -> "Answer":
|
|
16
|
+
kind = raw["type"]
|
|
17
|
+
value = raw.get(kind)
|
|
18
|
+
probabilities = raw.get("probabilities")
|
|
19
|
+
confidence = raw.get("confidence")
|
|
20
|
+
if kind == "noul":
|
|
21
|
+
if "probabilities" not in raw:
|
|
22
|
+
probabilities = {"false": 1 - value, "true": value}
|
|
23
|
+
if "confidence" not in raw:
|
|
24
|
+
confidence = max(value, 1 - value)
|
|
25
|
+
return cls(kind, value, probabilities, confidence, raw)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class Decision:
|
|
30
|
+
answers: dict[str, Answer]
|
|
31
|
+
model: str | None
|
|
32
|
+
usage: dict | None
|
|
33
|
+
raw: dict
|
|
34
|
+
nl_time: float | None = None
|
|
35
|
+
"""Seconds from sending the request to reading the full response."""
|
|
36
|
+
|
|
37
|
+
@classmethod
|
|
38
|
+
def from_raw(cls, raw: dict, *, nl_time: float | None = None) -> "Decision":
|
|
39
|
+
answers = {name: Answer.from_raw(answer) for name, answer in raw["answers"].items()}
|
|
40
|
+
return cls(answers, raw.get("model"), raw.get("usage"), raw, nl_time)
|
|
41
|
+
|
|
42
|
+
def __getitem__(self, name: str) -> Answer:
|
|
43
|
+
return self.answers[name]
|
|
44
|
+
|
|
45
|
+
def __contains__(self, name: str) -> bool:
|
|
46
|
+
return name in self.answers
|
|
47
|
+
|
|
48
|
+
def __iter__(self) -> Iterator[str]:
|
|
49
|
+
return iter(self.answers)
|
|
50
|
+
|
|
51
|
+
def __len__(self) -> int:
|
|
52
|
+
return len(self.answers)
|
noullama/client.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import errno
|
|
2
|
+
import json
|
|
3
|
+
import time
|
|
4
|
+
from collections.abc import Mapping
|
|
5
|
+
from http.client import HTTPException
|
|
6
|
+
from os import PathLike
|
|
7
|
+
from urllib.error import HTTPError, URLError
|
|
8
|
+
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
|
|
9
|
+
|
|
10
|
+
from .answers import Decision
|
|
11
|
+
from .config import DEFAULT_URL, normalize_base_url, resolve
|
|
12
|
+
from .errors import ModelUnavailable, NotRunning, NoullamaError, error_for
|
|
13
|
+
from .images import to_data_url
|
|
14
|
+
from .questions import Choice, Noul, Score, question_dict
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class _NoRedirects(HTTPRedirectHandler):
|
|
18
|
+
def http_error_302(self, request, response, code, message, headers):
|
|
19
|
+
# Let urllib's default error handler raise HTTPError for the original response.
|
|
20
|
+
return None
|
|
21
|
+
|
|
22
|
+
http_error_301 = http_error_303 = http_error_307 = http_error_308 = http_error_302
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
# No proxies: the gateway listens on 127.0.0.1 only, so a proxy can't reach it
|
|
26
|
+
# and would see the API key.
|
|
27
|
+
_OPENER = build_opener(ProxyHandler({}), _NoRedirects())
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class _RequestTimeout(NoullamaError):
|
|
31
|
+
pass
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Client:
|
|
35
|
+
def __init__(
|
|
36
|
+
self,
|
|
37
|
+
*,
|
|
38
|
+
base_url: str | None = None,
|
|
39
|
+
api_key: str | None = None,
|
|
40
|
+
timeout: float = 900.0,
|
|
41
|
+
):
|
|
42
|
+
url = resolve("NOULLAMA_URL", base_url)
|
|
43
|
+
self.base_url = normalize_base_url(DEFAULT_URL if url is None else url)
|
|
44
|
+
self._api_key = resolve("NOULLAMA_API_KEY", api_key)
|
|
45
|
+
self.timeout = timeout
|
|
46
|
+
|
|
47
|
+
def __repr__(self) -> str:
|
|
48
|
+
key = "***" if self._api_key else None
|
|
49
|
+
return f"Client(base_url={self._redact(self.base_url)!r}, api_key={key!r}, timeout={self.timeout!r})"
|
|
50
|
+
|
|
51
|
+
def health(self) -> dict:
|
|
52
|
+
return self._request("GET", "/health")
|
|
53
|
+
|
|
54
|
+
def models(self) -> list[str]:
|
|
55
|
+
return self._model_ids()
|
|
56
|
+
|
|
57
|
+
def _model_ids(self, *, timeout: float | None = None) -> list[str]:
|
|
58
|
+
response = self._request("GET", "/v1/models", timeout=timeout)
|
|
59
|
+
return [model["id"] for model in response["data"]]
|
|
60
|
+
|
|
61
|
+
def decide(
|
|
62
|
+
self,
|
|
63
|
+
*,
|
|
64
|
+
model: str,
|
|
65
|
+
state: str | dict | list,
|
|
66
|
+
questions: Mapping[str, Choice | Score | Noul | dict],
|
|
67
|
+
images: list[str | bytes | PathLike] | None = None,
|
|
68
|
+
winnow_temperature: float | None = None,
|
|
69
|
+
) -> Decision:
|
|
70
|
+
body = {
|
|
71
|
+
"model": model,
|
|
72
|
+
"state": state,
|
|
73
|
+
"questions": {name: question_dict(question) for name, question in questions.items()},
|
|
74
|
+
}
|
|
75
|
+
if images is not None:
|
|
76
|
+
body["images"] = [to_data_url(image) for image in images]
|
|
77
|
+
if winnow_temperature is not None:
|
|
78
|
+
body["winnow"] = {"temperature": winnow_temperature}
|
|
79
|
+
started = time.perf_counter()
|
|
80
|
+
raw = self._request("POST", "/v1/systemone", body)
|
|
81
|
+
return Decision.from_raw(raw, nl_time=time.perf_counter() - started)
|
|
82
|
+
|
|
83
|
+
def wait_until_ready(
|
|
84
|
+
self,
|
|
85
|
+
*,
|
|
86
|
+
model: str | None = None,
|
|
87
|
+
timeout: float = 60.0,
|
|
88
|
+
interval: float = 0.5,
|
|
89
|
+
) -> None:
|
|
90
|
+
deadline = time.monotonic() + timeout
|
|
91
|
+
while (remaining := deadline - time.monotonic()) > 0:
|
|
92
|
+
request_timeout = min(self.timeout, remaining)
|
|
93
|
+
ready = False
|
|
94
|
+
try:
|
|
95
|
+
if model is None:
|
|
96
|
+
ready = self._request("GET", "/health", timeout=request_timeout)["model_ready"]
|
|
97
|
+
else:
|
|
98
|
+
ready = model in self._model_ids(timeout=request_timeout)
|
|
99
|
+
except (NotRunning, ModelUnavailable):
|
|
100
|
+
pass
|
|
101
|
+
except _RequestTimeout:
|
|
102
|
+
if request_timeout < remaining and time.monotonic() < deadline:
|
|
103
|
+
raise
|
|
104
|
+
break
|
|
105
|
+
|
|
106
|
+
remaining = deadline - time.monotonic()
|
|
107
|
+
if remaining <= 0:
|
|
108
|
+
break
|
|
109
|
+
if ready:
|
|
110
|
+
return
|
|
111
|
+
time.sleep(min(interval, remaining))
|
|
112
|
+
|
|
113
|
+
raise TimeoutError(
|
|
114
|
+
self._redact(f"{model or 'A model'} was not ready after {timeout} seconds.")
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
def _redact(self, message: str) -> str:
|
|
118
|
+
return message.replace(self._api_key, "***") if self._api_key else message
|
|
119
|
+
|
|
120
|
+
def _open(self, method: str, path: str, body: dict | None, timeout: float):
|
|
121
|
+
headers = {}
|
|
122
|
+
if self._api_key:
|
|
123
|
+
headers["Authorization"] = f"Bearer {self._api_key}"
|
|
124
|
+
data = None
|
|
125
|
+
if body is not None:
|
|
126
|
+
headers["Content-Type"] = "application/json"
|
|
127
|
+
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
|
128
|
+
request = Request(self.base_url + path, data=data, headers=headers, method=method)
|
|
129
|
+
return _OPENER.open(request, timeout=timeout)
|
|
130
|
+
|
|
131
|
+
def _request(
|
|
132
|
+
self,
|
|
133
|
+
method: str,
|
|
134
|
+
path: str,
|
|
135
|
+
body: dict | None = None,
|
|
136
|
+
*,
|
|
137
|
+
timeout: float | None = None,
|
|
138
|
+
) -> dict:
|
|
139
|
+
timeout = self.timeout if timeout is None else timeout
|
|
140
|
+
timeout_message = self._redact(
|
|
141
|
+
f"No response from {self.base_url} within {timeout} seconds."
|
|
142
|
+
)
|
|
143
|
+
try:
|
|
144
|
+
try:
|
|
145
|
+
with self._open(method, path, body, timeout) as response:
|
|
146
|
+
payload = response.read()
|
|
147
|
+
status = response.getcode()
|
|
148
|
+
except HTTPError as error:
|
|
149
|
+
with error:
|
|
150
|
+
if 300 <= error.code < 400:
|
|
151
|
+
raise NoullamaError(
|
|
152
|
+
"Noullama answered with a redirect to another address; check NOULLAMA_URL.",
|
|
153
|
+
error.code,
|
|
154
|
+
) from None
|
|
155
|
+
text = error.read().decode("utf-8", errors="replace")
|
|
156
|
+
try:
|
|
157
|
+
message = json.loads(text)["error"]["message"]
|
|
158
|
+
except (ValueError, KeyError, TypeError):
|
|
159
|
+
message = None
|
|
160
|
+
if isinstance(message, str):
|
|
161
|
+
raise error_for(error.code, self._redact(message)) from None
|
|
162
|
+
raise NoullamaError(self._redact(text), error.code) from None
|
|
163
|
+
except URLError as error:
|
|
164
|
+
reason = error.reason
|
|
165
|
+
if isinstance(reason, OSError) and reason.errno == errno.ECONNREFUSED:
|
|
166
|
+
message = (
|
|
167
|
+
f"Noullama is not running at {self.base_url}. "
|
|
168
|
+
"Open the app, or set NOULLAMA_URL."
|
|
169
|
+
)
|
|
170
|
+
raise NotRunning(self._redact(message)) from None
|
|
171
|
+
if isinstance(reason, TimeoutError):
|
|
172
|
+
raise _RequestTimeout(timeout_message) from None
|
|
173
|
+
raise NoullamaError(self._redact(str(error))) from None
|
|
174
|
+
except TimeoutError:
|
|
175
|
+
raise _RequestTimeout(timeout_message) from None
|
|
176
|
+
except (HTTPException, OSError, ValueError) as error:
|
|
177
|
+
raise NoullamaError(self._redact(str(error))) from None
|
|
178
|
+
try:
|
|
179
|
+
return json.loads(payload)
|
|
180
|
+
except ValueError:
|
|
181
|
+
message = f"Noullama sent a response that isn't JSON (status {status})."
|
|
182
|
+
raise NoullamaError(self._redact(message), status) from None
|
noullama/config.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from collections.abc import Mapping
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
DEFAULT_URL = "http://127.0.0.1:11435"
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def read_dotenv(path: Path) -> dict[str, str]:
|
|
9
|
+
try:
|
|
10
|
+
lines = path.read_text(encoding="utf-8-sig").splitlines()
|
|
11
|
+
except (OSError, UnicodeError):
|
|
12
|
+
return {}
|
|
13
|
+
|
|
14
|
+
values = {}
|
|
15
|
+
for line in lines:
|
|
16
|
+
line = line.strip()
|
|
17
|
+
if not line or line.startswith("#"):
|
|
18
|
+
continue
|
|
19
|
+
key, separator, value = line.removeprefix("export ").partition("=")
|
|
20
|
+
key = key.strip()
|
|
21
|
+
if not separator or key not in {"NOULLAMA_API_KEY", "NOULLAMA_URL"}:
|
|
22
|
+
continue
|
|
23
|
+
value = value.strip()
|
|
24
|
+
if len(value) >= 2 and value[0] in ("'", '"') and value[-1] == value[0]:
|
|
25
|
+
value = value[1:-1]
|
|
26
|
+
values[key] = value
|
|
27
|
+
return values
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def resolve(
|
|
31
|
+
name: str,
|
|
32
|
+
explicit: str | None,
|
|
33
|
+
*,
|
|
34
|
+
environ: Mapping[str, str] | None = None,
|
|
35
|
+
dotenv: Path | None = None,
|
|
36
|
+
) -> str | None:
|
|
37
|
+
if explicit is not None:
|
|
38
|
+
return explicit
|
|
39
|
+
environ = os.environ if environ is None else environ
|
|
40
|
+
if name in environ:
|
|
41
|
+
return environ[name]
|
|
42
|
+
dotenv = Path.cwd() / ".env" if dotenv is None else dotenv
|
|
43
|
+
return read_dotenv(dotenv).get(name)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def normalize_base_url(url: str) -> str:
|
|
47
|
+
return url.rstrip("/").removesuffix("/v1")
|
noullama/errors.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
class NoullamaError(Exception):
|
|
2
|
+
def __init__(self, message: str, status: int | None = None):
|
|
3
|
+
super().__init__(message)
|
|
4
|
+
self.message = message
|
|
5
|
+
self.status = status
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class BadRequest(NoullamaError):
|
|
9
|
+
pass
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class AuthError(NoullamaError):
|
|
13
|
+
pass
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Forbidden(NoullamaError):
|
|
17
|
+
pass
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class UnknownModel(NoullamaError):
|
|
21
|
+
pass
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class AmbiguousModel(NoullamaError):
|
|
25
|
+
pass
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class InferenceFailed(NoullamaError):
|
|
29
|
+
pass
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class ModelUnavailable(NoullamaError):
|
|
33
|
+
pass
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class NotRunning(NoullamaError):
|
|
37
|
+
pass
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
_STATUS_ERRORS = {
|
|
41
|
+
400: BadRequest,
|
|
42
|
+
401: AuthError,
|
|
43
|
+
403: Forbidden,
|
|
44
|
+
404: UnknownModel,
|
|
45
|
+
409: AmbiguousModel,
|
|
46
|
+
502: InferenceFailed,
|
|
47
|
+
503: ModelUnavailable,
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def error_for(status: int, message: str) -> NoullamaError:
|
|
52
|
+
return _STATUS_ERRORS.get(status, NoullamaError)(message, status)
|
noullama/images.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
import mimetypes
|
|
3
|
+
from os import PathLike
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
_SIGNATURES = (
|
|
7
|
+
(b"\x89PNG\r\n\x1a\n", "image/png"),
|
|
8
|
+
(b"\xff\xd8\xff", "image/jpeg"),
|
|
9
|
+
(b"GIF87a", "image/gif"),
|
|
10
|
+
(b"GIF89a", "image/gif"),
|
|
11
|
+
(b"BM", "image/bmp"),
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def to_data_url(image: str | bytes | PathLike) -> str:
|
|
16
|
+
if isinstance(image, str) and image.startswith("data:"):
|
|
17
|
+
return image
|
|
18
|
+
|
|
19
|
+
path = None if isinstance(image, bytes) else Path(image)
|
|
20
|
+
data = image if path is None else path.read_bytes()
|
|
21
|
+
mime = next((kind for signature, kind in _SIGNATURES if data.startswith(signature)), None)
|
|
22
|
+
if data.startswith(b"RIFF") and data[8:12] == b"WEBP":
|
|
23
|
+
mime = "image/webp"
|
|
24
|
+
if mime is None and path is not None:
|
|
25
|
+
mime, _ = mimetypes.guess_type(str(path))
|
|
26
|
+
if mime is None or not mime.startswith(("image/", "audio/")):
|
|
27
|
+
name = str(path) if path is not None else "bytes"
|
|
28
|
+
raise ValueError(f"Can't tell the image type of {name}; pass a data: URL instead.")
|
|
29
|
+
|
|
30
|
+
encoded = base64.b64encode(data).decode("ascii")
|
|
31
|
+
return f"data:{mime};base64,{encoded}"
|
noullama/py.typed
ADDED
|
File without changes
|
noullama/questions.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
|
|
3
|
+
Instructions = str | dict | list
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
# The checks below return an error message (or None) instead of raising, so the
|
|
7
|
+
# error is raised from the question class and the traceback points at the
|
|
8
|
+
# caller's own line.
|
|
9
|
+
|
|
10
|
+
def _instructions_problem(question: str, instructions) -> tuple[type, str] | None:
|
|
11
|
+
if not isinstance(instructions, (str, dict, list)):
|
|
12
|
+
return TypeError, (
|
|
13
|
+
f"{question} instructions must be text, a dict or a list, "
|
|
14
|
+
f"not {type(instructions).__name__}."
|
|
15
|
+
)
|
|
16
|
+
if not (instructions.strip() if isinstance(instructions, str) else instructions):
|
|
17
|
+
return ValueError, (
|
|
18
|
+
f"{question} instructions are empty. Write the question, "
|
|
19
|
+
f'like instructions="Which team should handle this?".'
|
|
20
|
+
)
|
|
21
|
+
return None
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _blank(description) -> bool:
|
|
25
|
+
# None means "no description"; an empty or blank text is almost always a slip.
|
|
26
|
+
return isinstance(description, str) and not description.strip()
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class Choice:
|
|
30
|
+
def __init__(
|
|
31
|
+
self,
|
|
32
|
+
*,
|
|
33
|
+
instructions: Instructions,
|
|
34
|
+
criteria: dict[str, str | None] | None = None,
|
|
35
|
+
**options: str | None,
|
|
36
|
+
):
|
|
37
|
+
if criteria is not None and options:
|
|
38
|
+
raise TypeError("Choice takes either criteria={...} or named options, not both.")
|
|
39
|
+
if problem := _instructions_problem("Choice", instructions):
|
|
40
|
+
raise problem[0](problem[1])
|
|
41
|
+
self.instructions = instructions
|
|
42
|
+
self.criteria = options if criteria is None else criteria
|
|
43
|
+
for name, description in self.criteria.items():
|
|
44
|
+
if _blank(description):
|
|
45
|
+
raise ValueError(
|
|
46
|
+
f'Choice option "{name}" has an empty description. '
|
|
47
|
+
f'Write what it covers, like {name}="...", '
|
|
48
|
+
f"or use {name}=None if it needs no description."
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
def to_dict(self) -> dict:
|
|
52
|
+
return {"type": "choice", "instructions": self.instructions, "criteria": self.criteria}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True, kw_only=True)
|
|
56
|
+
class Score:
|
|
57
|
+
instructions: Instructions
|
|
58
|
+
levels: list[str]
|
|
59
|
+
|
|
60
|
+
def __post_init__(self):
|
|
61
|
+
if problem := _instructions_problem("Score", self.instructions):
|
|
62
|
+
raise problem[0](problem[1])
|
|
63
|
+
for index, level in enumerate(self.levels):
|
|
64
|
+
if _blank(level):
|
|
65
|
+
raise ValueError(
|
|
66
|
+
f"Score level {index} (counting from 0) is empty. "
|
|
67
|
+
f'Write what it means, like "Today", or use None to leave it undescribed.'
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
def to_dict(self) -> dict:
|
|
71
|
+
return {"type": "score", "instructions": self.instructions, "criteria": self.levels}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass(frozen=True, kw_only=True)
|
|
75
|
+
class Noul:
|
|
76
|
+
instructions: Instructions
|
|
77
|
+
true: str | None = None
|
|
78
|
+
false: str | None = None
|
|
79
|
+
|
|
80
|
+
def __post_init__(self):
|
|
81
|
+
if problem := _instructions_problem("Noul", self.instructions):
|
|
82
|
+
raise problem[0](problem[1])
|
|
83
|
+
for name in ("true", "false"):
|
|
84
|
+
if _blank(getattr(self, name)):
|
|
85
|
+
raise ValueError(
|
|
86
|
+
f'Noul {name}="" is empty. Describe what counts as {"yes" if name == "true" else "no"}, '
|
|
87
|
+
f"or leave {name} out (the same as {name}=None)."
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
def to_dict(self) -> dict:
|
|
91
|
+
result = {"type": "noul", "instructions": self.instructions}
|
|
92
|
+
criteria = {key: value for key, value in (("true", self.true), ("false", self.false))
|
|
93
|
+
if value is not None}
|
|
94
|
+
if criteria:
|
|
95
|
+
result["criteria"] = criteria
|
|
96
|
+
return result
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def question_dict(q: Choice | Score | Noul | dict) -> dict:
|
|
100
|
+
if isinstance(q, dict):
|
|
101
|
+
return q
|
|
102
|
+
if isinstance(q, (Choice, Score, Noul)):
|
|
103
|
+
return q.to_dict()
|
|
104
|
+
raise TypeError("Expected a Choice, Score, Noul or dict.")
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: noullama
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Ask decision models loaded in Noullama questions from Python.
|
|
5
|
+
Author: parasite6
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://noullama.dev
|
|
8
|
+
Project-URL: Source, https://github.com/Noullama/noullama/tree/sanctuary/python
|
|
9
|
+
Project-URL: Issues, https://github.com/Noullama/noullama/issues
|
|
10
|
+
Keywords: noullama,llama.cpp,decision models,classification,local llm
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
17
|
+
Classifier: Typing :: Typed
|
|
18
|
+
Requires-Python: >=3.10
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
License-File: LICENSE
|
|
21
|
+
Dynamic: license-file
|
|
22
|
+
|
|
23
|
+
# Noullama Python client
|
|
24
|
+
|
|
25
|
+
Ask a model loaded in Noullama questions from your own Python code.
|
|
26
|
+
|
|
27
|
+
## Install
|
|
28
|
+
|
|
29
|
+
Python 3.10 or newer. It has no dependencies.
|
|
30
|
+
|
|
31
|
+
```sh
|
|
32
|
+
python -m pip install noullama
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Using `python -m pip` makes sure the package goes into the same Python that runs your script.
|
|
36
|
+
|
|
37
|
+
## Quick start
|
|
38
|
+
|
|
39
|
+
Open Noullama and load a model first.
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from noullama import Choice, Client, Noul, Score
|
|
43
|
+
|
|
44
|
+
nl = Client()
|
|
45
|
+
|
|
46
|
+
decision = nl.decide(
|
|
47
|
+
model="d1-2B-Q8_0",
|
|
48
|
+
state="I was charged twice. Please refund the duplicate payment.",
|
|
49
|
+
questions={
|
|
50
|
+
"route": Choice(
|
|
51
|
+
instructions="Which team should handle this?",
|
|
52
|
+
billing="Charges and refunds",
|
|
53
|
+
technical="App errors",
|
|
54
|
+
),
|
|
55
|
+
"urgency": Score(
|
|
56
|
+
instructions="How urgent is this?",
|
|
57
|
+
levels=["Can wait", "This week", "Today", "Immediately"],
|
|
58
|
+
),
|
|
59
|
+
"refund": Noul(instructions="Is the customer asking for a refund?"),
|
|
60
|
+
},
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
answer = decision["route"]
|
|
64
|
+
print(answer.value) # billing
|
|
65
|
+
print(answer.probabilities) # {'billing': 0.98, 'technical': 0.02}
|
|
66
|
+
print(answer.confidence) # 0.98
|
|
67
|
+
print(decision.nl_time) # 0.025 (seconds the whole decision took)
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
- **`model`:** the model's name or alias as shown in the app's Local API tab. Use `any-available` for any free model.
|
|
71
|
+
- **`state`:** the text (or dict or list) you're asking about.
|
|
72
|
+
- **`questions`:** each question gets a name you choose (`"route"` above). You use that name to read its answer.
|
|
73
|
+
- **`decision`, `answer` and `nl`** are ordinary variable names. Call them whatever you like.
|
|
74
|
+
|
|
75
|
+
## Questions
|
|
76
|
+
|
|
77
|
+
There are three types. Every question needs `instructions`, which can't be empty. Descriptions are optional: use `None` for no description. An empty one like `technical=""` is an error, so a forgotten description doesn't slip through.
|
|
78
|
+
|
|
79
|
+
**`Choice`: pick one option.** Each option is a name, plus an optional description that helps the model understand it. You get back the name.
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
Choice(instructions="Which team?", billing="Charges and refunds", technical="App errors")
|
|
83
|
+
Choice(instructions="Which team?", billing=None, technical=None) # no descriptions
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
**`Score`: pick a level on a scale.** List the levels lowest first, 2 to 10 of them. You get back the level's number, counting from 0.
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
Score(instructions="How urgent?", levels=["Can wait", "This week", "Today", "Immediately"])
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
**`Noul`: yes or no.** You get back the chance that the answer is yes, from 0 to 1.
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
Noul(instructions="Is this a refund request?")
|
|
96
|
+
Noul(instructions="Is this a refund request?", true="asks for money back") # optional descriptions
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## Answers
|
|
100
|
+
|
|
101
|
+
Every answer has the same three fields:
|
|
102
|
+
|
|
103
|
+
| Field | Choice | Score | Noul |
|
|
104
|
+
| --- | --- | --- | --- |
|
|
105
|
+
| `.value` | the picked option, e.g. `"billing"` | the picked level, e.g. `2.0` | chance of yes, e.g. `0.93` |
|
|
106
|
+
| `.probabilities` | chance per option | chance per level (`"0"`, `"1"`, …) | `{"false": 0.07, "true": 0.93}` |
|
|
107
|
+
| `.confidence` | how sure the model is, 0 to 1 | same | same |
|
|
108
|
+
|
|
109
|
+
Native models only send the yes chance for `Noul`, so the client works out `.probabilities` and `.confidence` from it.
|
|
110
|
+
|
|
111
|
+
Native and Winnow models count `Score` and `confidence` differently. Native models give the most likely level and its chance. Winnow models give a weighted average level and an entropy-based confidence. The client shows what the model sends.
|
|
112
|
+
|
|
113
|
+
The decision as a whole has these:
|
|
114
|
+
|
|
115
|
+
- **`decision.nl_time`:** seconds from sending the request to getting the full reply. All questions share one request, so there's one time per decision.
|
|
116
|
+
- **`decision.model` and `decision.usage`:** the model name and token counts.
|
|
117
|
+
- **`decision.raw` and `answer.raw`:** the untouched reply, for anything else, such as a Score's `legend`.
|
|
118
|
+
|
|
119
|
+
## Settings and the API key
|
|
120
|
+
|
|
121
|
+
`Client()` finds the app's address and your API key, then waits. It sends nothing until you call it. It checks these places in order and uses the first value it finds:
|
|
122
|
+
|
|
123
|
+
1. Arguments: `Client(base_url="http://127.0.0.1:11440", api_key="da-noul-...")`
|
|
124
|
+
2. Environment variables `NOULLAMA_URL` and `NOULLAMA_API_KEY`
|
|
125
|
+
3. A `.env` file in the folder you run from, with the same names
|
|
126
|
+
4. Defaults: `http://127.0.0.1:11435` and no key
|
|
127
|
+
|
|
128
|
+
You only need a key when **Require API key** is on in the app. Keep it out of your code with a `.env` file:
|
|
129
|
+
|
|
130
|
+
```dotenv
|
|
131
|
+
NOULLAMA_API_KEY=da-noul-...
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
The address can be pasted from the Local API tab as is, `/v1` included. The key never appears in printouts or error messages.
|
|
135
|
+
|
|
136
|
+
Make one client and reuse it, for example in a loop:
|
|
137
|
+
|
|
138
|
+
```python
|
|
139
|
+
nl = Client()
|
|
140
|
+
for email in inbox:
|
|
141
|
+
decision = nl.decide(model="d1-2B-Q8_0", state=email, questions=questions)
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
## More
|
|
145
|
+
|
|
146
|
+
- **`nl.models()`:** the model names you can use right now.
|
|
147
|
+
- **`nl.health()`:** whether the app is up and a model is ready.
|
|
148
|
+
- **`nl.wait_until_ready(model="d1-2B-Q8_0", timeout=60)`:** waits until that model is ready. Leave out `model` to wait for any model.
|
|
149
|
+
- **Images:** pass `images=["receipt.png"]` to `decide()`. This only works with models that have a vision projector. Winnow models are text only.
|
|
150
|
+
|
|
151
|
+
## Errors
|
|
152
|
+
|
|
153
|
+
Each problem has its own exception, so you can catch the ones you care about:
|
|
154
|
+
|
|
155
|
+
```python
|
|
156
|
+
from noullama import Client, ModelUnavailable, NotRunning, Noul
|
|
157
|
+
|
|
158
|
+
try:
|
|
159
|
+
decision = Client().decide(
|
|
160
|
+
model="d1-2B-Q8_0",
|
|
161
|
+
state="Please refund my duplicate payment.",
|
|
162
|
+
questions={"refund": Noul(instructions="Is this a refund request?")},
|
|
163
|
+
)
|
|
164
|
+
except NotRunning:
|
|
165
|
+
print("Open Noullama first")
|
|
166
|
+
except ModelUnavailable:
|
|
167
|
+
print("That model isn't loaded yet")
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
| Exception | Meaning |
|
|
171
|
+
| --- | --- |
|
|
172
|
+
| `NotRunning` | The app isn't open, or isn't at that address |
|
|
173
|
+
| `ModelUnavailable` | The model isn't loaded, is still loading, or every model is busy |
|
|
174
|
+
| `UnknownModel` | No model has that name (names are case-sensitive) |
|
|
175
|
+
| `AmbiguousModel` | The name matches more than one model |
|
|
176
|
+
| `BadRequest` | Something in the request is wrong. The message says what |
|
|
177
|
+
| `AuthError` | The API key is missing, wrong or expired |
|
|
178
|
+
| `Forbidden` | The API key isn't allowed to use this model |
|
|
179
|
+
| `InferenceFailed` | The model failed while answering |
|
|
180
|
+
| `NoullamaError` | The base class of all of the above; catches everything |
|
|
181
|
+
|
|
182
|
+
Every exception has `.message` (the app's own wording) and `.status` (the HTTP status code).
|
|
183
|
+
|
|
184
|
+
## Tested with
|
|
185
|
+
|
|
186
|
+
Noullama 0.5.4.
|
|
187
|
+
|
|
188
|
+
## License
|
|
189
|
+
|
|
190
|
+
The Python client is [MIT-licensed](https://github.com/Noullama/noullama/blob/sanctuary/python/LICENSE). The rest of Noullama is AGPL-3.0.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
noullama/__init__.py,sha256=hoYSgPfuexPBQJXFXRAfiw6jZ0pmD8uFo2KcGBix5_c,614
|
|
2
|
+
noullama/answers.py,sha256=jUxeozJX0frXoPSKAxfDu8OdxDD7nrDv7BLw9OluMBg,1544
|
|
3
|
+
noullama/client.py,sha256=sB3w2gthsKPyYYHCxvMKah3GjV8-lmXdUE1uFIbP53E,7028
|
|
4
|
+
noullama/config.py,sha256=mml044dgWQBgPuLCwo3IJBtYVrqTqUEruBZ4LosmdKY,1327
|
|
5
|
+
noullama/errors.py,sha256=TJ260BbLbgJ7XCOvVAsOyui84O2nvVABB6iFmzNtnkU,874
|
|
6
|
+
noullama/images.py,sha256=4c4EkSvCGpNQ8Lxz7pZPNFtyd5XNzSjXsJDyjOmWx20,1107
|
|
7
|
+
noullama/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
noullama/questions.py,sha256=A_TpFRyEo4I2eflfDqLz8BHy29WFjMhGz3eFR2ZGMF4,3872
|
|
9
|
+
noullama-0.2.0.dist-info/licenses/LICENSE,sha256=wnhcCm_-_fhKs473IaDE0DPuO1ETiT4UxOEfOo-cS9w,1066
|
|
10
|
+
noullama-0.2.0.dist-info/METADATA,sha256=hU1xahbFwpyXtx9i3wpuXf4YpPxi4o_jykWgzRdasqY,7448
|
|
11
|
+
noullama-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
12
|
+
noullama-0.2.0.dist-info/top_level.txt,sha256=ZfprMqAWShVLvQfN63gDayuQE0btfmnb_h-r4_00wHk,9
|
|
13
|
+
noullama-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 parasite6
|
|
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
|
+
noullama
|