launchables 0.4.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.
@@ -0,0 +1,39 @@
1
+ """Python client for the Launchables Decision API."""
2
+
3
+ from ._version import __version__
4
+ from .admin import AdminKeys
5
+ from .client import DEFAULT_ADMIN_BASE_URL, DEFAULT_BASE_URL, KEY_EXPIRY_WARNING_DAYS, KeyExpiryWarning, Launchables
6
+ from .errors import (
7
+ APIConnectionError,
8
+ APIError,
9
+ AuthenticationError,
10
+ ConflictError,
11
+ InvalidRequestError,
12
+ LaunchablesError,
13
+ NotFoundError,
14
+ OutOfCreditError,
15
+ PermissionDeniedError,
16
+ RateLimitError,
17
+ ValidationError,
18
+ )
19
+ from .images import IMAGE_BUDGETS, IMAGE_FORMATS, MAX_IMAGE_BYTES, Image
20
+ from .questions import choice, noul, score
21
+ from .responses import (
22
+ ChoiceAnswer,
23
+ DecisionResponse,
24
+ KeyExpiry,
25
+ KeyInfo,
26
+ Model,
27
+ NoulAnswer,
28
+ ScoreAnswer,
29
+ Usage,
30
+ )
31
+
32
+ __all__ = [
33
+ "__version__", "Launchables", "DEFAULT_BASE_URL", "DEFAULT_ADMIN_BASE_URL", "AdminKeys", "KEY_EXPIRY_WARNING_DAYS", "KeyExpiryWarning", "KeyInfo", "KeyExpiry",
34
+ "noul", "choice", "score", "Image", "IMAGE_BUDGETS", "IMAGE_FORMATS", "MAX_IMAGE_BYTES",
35
+ "DecisionResponse", "NoulAnswer", "ChoiceAnswer", "ScoreAnswer", "Usage", "Model",
36
+ "LaunchablesError", "AuthenticationError", "OutOfCreditError", "PermissionDeniedError",
37
+ "RateLimitError", "InvalidRequestError", "NotFoundError", "ConflictError",
38
+ "ValidationError", "APIError", "APIConnectionError",
39
+ ]
@@ -0,0 +1 @@
1
+ __version__ = "0.4.0"
launchables/admin.py ADDED
@@ -0,0 +1,80 @@
1
+ """The key management API: list, create, roll and revoke your organisation's API keys with an admin key."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import urllib.parse
6
+ from typing import TYPE_CHECKING, Any, Dict, Iterator, Optional
7
+
8
+ from .errors import ValidationError
9
+
10
+ if TYPE_CHECKING:
11
+ from .client import Launchables
12
+
13
+ KEYS_PATH = "/api/v1/admin/keys"
14
+
15
+
16
+ def _key_path(key_id: str) -> str:
17
+ if not isinstance(key_id, str) or not key_id:
18
+ raise ValidationError('key_id must be a key id, e.g. "c_1a2b3c4d"')
19
+ return f"{KEYS_PATH}/{urllib.parse.quote(key_id, safe='')}"
20
+
21
+
22
+ class AdminKeys:
23
+ """The organisation's API keys, through the key management API. Needs an admin key.
24
+
25
+ Responses are the API's JSON as dictionaries. A key in a list never includes the secret; ``create`` and ``roll``
26
+ return the new key's full secret under ``"key"``, once.
27
+ """
28
+
29
+ def __init__(self, client: "Launchables") -> None:
30
+ self._client = client
31
+
32
+ def list(self, limit: Optional[int] = None, before: Optional[str] = None) -> Dict[str, Any]:
33
+ """One page of the organisation's keys, newest first: ``{"data": [...], "has_more": bool, "next_before": str | None}``.
34
+ When ``has_more`` is true, pass ``next_before`` as ``before`` to get the next page. ``limit`` is 1 to 500 (default 100)."""
35
+ params = {}
36
+ if limit is not None:
37
+ params["limit"] = str(limit)
38
+ if before is not None:
39
+ params["before"] = before
40
+ query = urllib.parse.urlencode(params)
41
+ return self._client._admin_request("GET", KEYS_PATH + (f"?{query}" if query else ""))
42
+
43
+ def list_all(self, limit: Optional[int] = None) -> Iterator[Dict[str, Any]]:
44
+ """Every key, newest first, fetching pages as needed."""
45
+ before: Optional[str] = None
46
+ while True:
47
+ page = self.list(limit=limit, before=before)
48
+ for key in page.get("data", []):
49
+ yield key
50
+ if not page.get("has_more") or not page.get("next_before"):
51
+ return
52
+ before = page["next_before"]
53
+
54
+ def create(self, name: str, workspace_id: Optional[str] = None, expires_in_days: Optional[int] = None) -> Dict[str, Any]:
55
+ """Make a new key. ``workspace_id`` defaults to the organisation's default workspace; ``expires_in_days`` is 30,
56
+ 90, 180 or 365 (default 90, never longer than the organisation allows). The response holds the full key, once."""
57
+ if not isinstance(name, str) or not name.strip():
58
+ raise ValidationError("name is required")
59
+ body: Dict[str, Any] = {"name": name}
60
+ if workspace_id is not None:
61
+ body["workspace_id"] = workspace_id
62
+ if expires_in_days is not None:
63
+ body["expires_in_days"] = expires_in_days
64
+ return self._client._admin_request("POST", KEYS_PATH, body)
65
+
66
+ def roll(self, key_id: str) -> Dict[str, Any]:
67
+ """Replace a key with a new one (same name, workspace and limits). The old key keeps working until the end of
68
+ tomorrow; the response says when, under ``"replaces"``."""
69
+ return self._client._admin_request("POST", _key_path(key_id) + "/roll")
70
+
71
+ def revoke(self, key_id: str) -> Dict[str, Any]:
72
+ """Revoke a key. It stops working within a minute. Revoking a revoked key is not an error."""
73
+ return self._client._admin_request("DELETE", _key_path(key_id))
74
+
75
+
76
+ class Admin:
77
+ """``client.admin``: the key management API."""
78
+
79
+ def __init__(self, client: "Launchables") -> None:
80
+ self.keys = AdminKeys(client)
launchables/client.py ADDED
@@ -0,0 +1,267 @@
1
+ """The Launchables client (standard library only)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime
6
+ import json
7
+ import os
8
+ import socket
9
+ import time
10
+ import urllib.error
11
+ import urllib.request
12
+ import warnings
13
+ from typing import Any, Callable, Dict, List, Mapping, Optional, Union
14
+
15
+ from ._version import __version__
16
+ from .errors import (
17
+ APIConnectionError,
18
+ AuthenticationError,
19
+ LaunchablesError,
20
+ ValidationError,
21
+ error_for_status,
22
+ )
23
+ from .admin import Admin
24
+ from .images import Image, validate_assets, validate_image_budget
25
+ from .questions import validate_questions
26
+ from .responses import DecisionResponse, KeyExpiry, KeyInfo, Model, parse_key_info, parse_response
27
+
28
+ DEFAULT_BASE_URL = "https://api.launchables.ai"
29
+ DEFAULT_ADMIN_BASE_URL = "https://console.launchables.ai"
30
+ ENV_API_KEY = "LAUNCHABLES_API_TOKEN"
31
+ ENV_ADMIN_KEY = "LAUNCHABLES_ADMIN_KEY"
32
+ RETRY_STATUSES = frozenset({429, 502, 503})
33
+ BACKOFF_BASE = 0.5
34
+ MAX_RETRY_AFTER = 60.0
35
+ USER_AGENT = f"launchables-python/{__version__}"
36
+ KEY_EXPIRY_WARNING_DAYS = 14 # warn once when a key has this many days or fewer left
37
+
38
+
39
+ class KeyExpiryWarning(UserWarning):
40
+ """Issued once per client when the API key has 14 days or fewer left and no ``on_key_expiry`` callback is set."""
41
+
42
+
43
+ def _days_until(date: str) -> Optional[int]:
44
+ """Whole days from today (UTC) to a YYYY-MM-DD date, or None if it is not one."""
45
+ try:
46
+ end = datetime.date.fromisoformat(date)
47
+ except (TypeError, ValueError):
48
+ return None
49
+ return (end - datetime.datetime.now(datetime.timezone.utc).date()).days
50
+
51
+ _sleep = time.sleep # patched in tests
52
+
53
+
54
+ def _parse_retry_after(value: Optional[str]) -> Optional[float]:
55
+ if not value:
56
+ return None
57
+ try:
58
+ seconds = float(value)
59
+ except ValueError:
60
+ return None # HTTP-date form is not supported; fall back to backoff
61
+ return max(0.0, seconds)
62
+
63
+
64
+ class Launchables:
65
+ """Client for the Launchables Decision API.
66
+
67
+ >>> client = Launchables() # reads LAUNCHABLES_API_TOKEN
68
+ """
69
+
70
+ def __init__(
71
+ self,
72
+ api_key: Optional[str] = None,
73
+ base_url: str = DEFAULT_BASE_URL,
74
+ timeout: float = 30,
75
+ max_retries: int = 3,
76
+ on_key_expiry: Optional[Callable[[KeyExpiry], None]] = None,
77
+ admin_key: Optional[str] = None,
78
+ admin_base_url: str = DEFAULT_ADMIN_BASE_URL,
79
+ ) -> None:
80
+ """``on_key_expiry`` is called once per key and expiry date when a response shows the key has 14 days or fewer left, so you can
81
+ rotate it on time; without it, the client issues one ``KeyExpiryWarning`` instead.
82
+
83
+ ``admin_key`` (or the ``LAUNCHABLES_ADMIN_KEY`` environment variable) is an admin key, starting
84
+ ``launchables_admin_``, for ``client.admin.keys``. It manages your organisation's API keys and cannot call the
85
+ Decision API."""
86
+ if max_retries < 0:
87
+ raise ValueError("max_retries must be >= 0")
88
+ self.api_key = api_key
89
+ self.base_url = base_url.rstrip("/")
90
+ self.timeout = timeout
91
+ self.max_retries = max_retries
92
+ self.on_key_expiry = on_key_expiry
93
+ self.key_expiry: Optional[KeyExpiry] = None # the key's expiry as last seen in a response
94
+ self._warned_for: set = set() # every key and expiry date warned about: once per pair
95
+ self.admin_key = admin_key
96
+ self.admin_base_url = admin_base_url.rstrip("/")
97
+ #: The key management API: ``admin.keys.list()``, ``create()``, ``roll()`` and ``revoke()``. Needs an admin key.
98
+ self.admin = Admin(self)
99
+
100
+ # -- public API --------------------------------------------------------
101
+
102
+ def decide(
103
+ self,
104
+ state: Union[str, Mapping[str, Any]],
105
+ questions: Mapping[str, Mapping[str, Any]],
106
+ model: Optional[str] = None,
107
+ *,
108
+ assets: Optional[Mapping[str, Union[Image, Mapping[str, Any]]]] = None,
109
+ image_budget: Optional[int] = None,
110
+ ) -> DecisionResponse:
111
+ """Ask one or more questions about ``state`` (a string or a JSON object).
112
+
113
+ ``assets`` maps a reference to an image (``Image.from_path``, ``Image.from_bytes``, or a dict already in the
114
+ ``{"type": "image", "format", "data_base64"}`` shape). Wherever the reference appears as text in the state (any
115
+ string value), a question's instructions or a criterion's description, the model sees the image there. Option
116
+ labels are not searched. Every asset must be referenced at least once.
117
+
118
+ ``image_budget`` (70, 140 or 280) is the most visual tokens one image may use; the server uses 280 when it is
119
+ not given. Lower is cheaper and faster but sees less detail."""
120
+ key = self._resolve_key()
121
+ if not isinstance(state, (str, Mapping)):
122
+ raise ValidationError("state must be a string or a JSON object (dict)")
123
+ body: Dict[str, Any] = {"state": state, "questions": validate_questions(questions)}
124
+ if model is not None:
125
+ body["model"] = model
126
+ if assets is not None:
127
+ body["assets"] = validate_assets(assets)
128
+ if image_budget is not None:
129
+ body["image_budget"] = validate_image_budget(image_budget)
130
+ data = self._request("POST", "/v1/decide", body, key)
131
+ return parse_response(data)
132
+
133
+ def models(self) -> List[Model]:
134
+ # the key is optional here; when there is one, the response also tells the client when it expires
135
+ data = self._request("GET", "/v1/models", key=self.api_key or os.environ.get(ENV_API_KEY))
136
+ return [
137
+ Model(id=m["id"], owned_by=m.get("owned_by", ""), raw=m)
138
+ for m in data.get("data", [])
139
+ ]
140
+
141
+ def key(self) -> KeyInfo:
142
+ """Details of the key this client uses: id, name, when it expires and how many days are left, its limits, and
143
+ whether it is paused (and why). It counts as no request and no tokens."""
144
+ return parse_key_info(self._request("GET", "/v1/key", key=self._resolve_key()))
145
+
146
+ def health(self) -> Dict[str, Any]:
147
+ """Returns the server's health payload, e.g. ``{"status": "ok"}``."""
148
+ return self._request("GET", "/health")
149
+
150
+ # -- internals ---------------------------------------------------------
151
+
152
+ def _resolve_key(self) -> str:
153
+ key = self.api_key or os.environ.get(ENV_API_KEY)
154
+ if not key:
155
+ raise AuthenticationError(
156
+ f"No API key. Pass api_key=... or set the {ENV_API_KEY} environment variable."
157
+ )
158
+ return key
159
+
160
+ def _resolve_admin_key(self) -> str:
161
+ key = self.admin_key or os.environ.get(ENV_ADMIN_KEY)
162
+ if not key:
163
+ raise AuthenticationError(
164
+ f"No admin key. Pass admin_key=... or set the {ENV_ADMIN_KEY} environment variable. "
165
+ "An owner makes one on the API keys page of the console."
166
+ )
167
+ return key
168
+
169
+ def _admin_request(self, method: str, path: str, body: Any = None) -> Dict[str, Any]:
170
+ return self._request(method, path, body, self._resolve_admin_key(), base_url=self.admin_base_url, admin=True)
171
+
172
+ def _note_key_headers(self, headers: Any) -> None:
173
+ """Reads the key headers every response to a keyed request carries, and warns once when expiry is close."""
174
+ expires = headers.get("Launchables-Key-Expires") if headers else None
175
+ if not expires:
176
+ return
177
+ days = _days_until(expires)
178
+ if days is None:
179
+ return
180
+ self.key_expiry = KeyExpiry(key_id=headers.get("Launchables-Key-Id"), expires_on=expires, days_left=days)
181
+ which = f"{self.key_expiry.key_id or ''}|{expires}"
182
+ if days > KEY_EXPIRY_WARNING_DAYS or which in self._warned_for:
183
+ return
184
+ self._warned_for.add(which)
185
+ try:
186
+ if self.on_key_expiry is not None:
187
+ self.on_key_expiry(self.key_expiry)
188
+ else:
189
+ warnings.warn(
190
+ f"Launchables API key {self.key_expiry.key_id or ''} expires on {expires} ({days} day"
191
+ f"{'' if days == 1 else 's'} left). Roll it in the console to replace it without downtime.",
192
+ KeyExpiryWarning, stacklevel=4,
193
+ )
194
+ except Exception: # noqa: BLE001 a failing callback must never break the request it rode on
195
+ pass
196
+
197
+ def _request(
198
+ self, method: str, path: str, body: Any = None, key: Optional[str] = None,
199
+ base_url: Optional[str] = None, admin: bool = False,
200
+ ) -> Dict[str, Any]:
201
+ headers = {"User-Agent": USER_AGENT, "Accept": "application/json"}
202
+ payload = None
203
+ if key:
204
+ headers["Authorization"] = f"Bearer {key}"
205
+ if body is not None:
206
+ payload = json.dumps(body).encode("utf-8")
207
+ headers["Content-Type"] = "application/json"
208
+ base_url = self.base_url if base_url is None else base_url # never the Decision API for an admin call
209
+ url = base_url + path
210
+ # a key management POST (create, roll) is retried only when the server refused it unrun (429), so a retry never
211
+ # makes two keys
212
+ once = admin and method == "POST"
213
+ note = key and not admin
214
+
215
+ attempt = 0
216
+ while True:
217
+ req = urllib.request.Request(url, data=payload, headers=headers, method=method)
218
+ retry_after: Optional[float] = None
219
+ try:
220
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
221
+ if note:
222
+ self._note_key_headers(resp.headers)
223
+ return self._decode(resp.read(), resp.status)
224
+ except urllib.error.HTTPError as e:
225
+ raw = e.read()
226
+ if note:
227
+ self._note_key_headers(e.headers)
228
+ retry_after = _parse_retry_after(e.headers.get("Retry-After") if e.headers else None)
229
+ err: LaunchablesError = self._http_error(e.code, raw, retry_after)
230
+ retryable = e.code in RETRY_STATUSES and (not once or e.code == 429)
231
+ except (urllib.error.URLError, socket.timeout, ConnectionError, TimeoutError) as e:
232
+ reason = getattr(e, "reason", e)
233
+ err = APIConnectionError(f"Could not reach {base_url}: {reason}")
234
+ err.__cause__ = e
235
+ retryable = not once
236
+ if not retryable or attempt >= self.max_retries:
237
+ raise err
238
+ delay = retry_after if retry_after is not None else BACKOFF_BASE * (2 ** attempt)
239
+ _sleep(min(delay, MAX_RETRY_AFTER))
240
+ attempt += 1
241
+
242
+ @staticmethod
243
+ def _decode(raw: bytes, status: int) -> Dict[str, Any]:
244
+ try:
245
+ data = json.loads(raw.decode("utf-8"))
246
+ except (ValueError, UnicodeDecodeError):
247
+ raise LaunchablesError("Server returned a non-JSON response", status, raw[:500]) from None
248
+ if not isinstance(data, dict):
249
+ raise LaunchablesError("Server returned an unexpected response", status, data)
250
+ return data
251
+
252
+ @staticmethod
253
+ def _http_error(status: int, raw: bytes, retry_after: Optional[float]) -> LaunchablesError:
254
+ message = f"HTTP {status}"
255
+ body: Any = None
256
+ try:
257
+ body = json.loads(raw.decode("utf-8"))
258
+ if isinstance(body, dict) and isinstance(body.get("error"), str):
259
+ message = body["error"]
260
+ # the key management API sends {"error": {"type", "message"}}
261
+ elif isinstance(body, dict) and isinstance(body.get("error"), dict) and isinstance(body["error"].get("message"), str):
262
+ message = body["error"]["message"]
263
+ except (ValueError, UnicodeDecodeError):
264
+ text = raw[:200].decode("utf-8", "replace").strip()
265
+ if text:
266
+ message = text
267
+ return error_for_status(status, message, body, retry_after)
launchables/errors.py ADDED
@@ -0,0 +1,99 @@
1
+ """Exception hierarchy for the Launchables client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Optional
6
+
7
+
8
+ class LaunchablesError(Exception):
9
+ """Base class for every error raised by this package."""
10
+
11
+ def __init__(
12
+ self,
13
+ message: str,
14
+ status: Optional[int] = None,
15
+ body: Any = None,
16
+ ) -> None:
17
+ super().__init__(message)
18
+ self.message = message
19
+ self.status = status
20
+ self.body = body
21
+ t = body.get("type") if isinstance(body, dict) else None
22
+ if t is None and isinstance(body, dict) and isinstance(body.get("error"), dict):
23
+ t = body["error"].get("type") # the key management API's {"error": {"type", "message"}}
24
+ #: The server's error type (e.g. "out_of_credit", "rate_limited"), or None if it sent none.
25
+ self.type: Optional[str] = t if isinstance(t, str) else None
26
+
27
+ def __str__(self) -> str:
28
+ if self.status is not None:
29
+ return f"{self.message} (HTTP {self.status})"
30
+ return self.message
31
+
32
+
33
+ class AuthenticationError(LaunchablesError):
34
+ """401: bad or missing token (also raised locally when no key is set)."""
35
+
36
+
37
+ class OutOfCreditError(LaunchablesError):
38
+ """402: no prepaid credit left (``type`` "out_of_credit") or the key's workspace has reached its
39
+ monthly budget (``type`` "budget_exceeded")."""
40
+
41
+
42
+ class PermissionDeniedError(LaunchablesError):
43
+ """403: the key's workspace may not use this model (``type`` "model_not_allowed"), or an admin key's maker is no
44
+ longer an owner."""
45
+
46
+
47
+ class RateLimitError(LaunchablesError):
48
+ """429: rate limit or daily limit reached."""
49
+
50
+ def __init__(self, message, status=429, body=None, retry_after=None):
51
+ super().__init__(message, status, body)
52
+ self.retry_after: Optional[float] = retry_after
53
+
54
+
55
+ class InvalidRequestError(LaunchablesError):
56
+ """400, 411, 413, 422 (and any other 4xx): the request cannot be answered.
57
+
58
+ For an image, ``type`` says what was wrong: "invalid_assets", "unsupported_image_format", "invalid_image",
59
+ "image_too_large", "image_dimensions", "too_many_images", "unreferenced_asset" or "image_reference_truncated"
60
+ (400), or "invalid_image_budget" (422). The message names the asset."""
61
+
62
+
63
+ class NotFoundError(InvalidRequestError):
64
+ """404: no such key or workspace in your organisation (key management API)."""
65
+
66
+
67
+ class ConflictError(InvalidRequestError):
68
+ """409: the change conflicts with the organisation's state, e.g. its key limit or an archived workspace (key
69
+ management API)."""
70
+
71
+
72
+ class ValidationError(InvalidRequestError, ValueError):
73
+ """Raised locally, before any request is sent, for malformed input."""
74
+
75
+
76
+ class APIError(LaunchablesError):
77
+ """5xx: the server failed (502 model did not respond, 503 maintenance)."""
78
+
79
+
80
+ class APIConnectionError(LaunchablesError):
81
+ """The server could not be reached (DNS, refused, reset, timeout)."""
82
+
83
+
84
+ def error_for_status(status, message, body=None, retry_after=None) -> LaunchablesError:
85
+ if status == 401:
86
+ return AuthenticationError(message, status, body)
87
+ if status == 402:
88
+ return OutOfCreditError(message, status, body)
89
+ if status == 403:
90
+ return PermissionDeniedError(message, status, body)
91
+ if status == 404:
92
+ return NotFoundError(message, status, body)
93
+ if status == 409:
94
+ return ConflictError(message, status, body)
95
+ if status == 429:
96
+ return RateLimitError(message, status, body, retry_after)
97
+ if 400 <= status < 500:
98
+ return InvalidRequestError(message, status, body)
99
+ return APIError(message, status, body)
launchables/images.py ADDED
@@ -0,0 +1,119 @@
1
+ """Image inputs for ``decide``: the ``Image`` helper and the checks run on ``assets`` and ``image_budget``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import os
7
+ from typing import Any, Dict, Mapping, Optional, Union
8
+
9
+ from .errors import ValidationError
10
+
11
+ #: The formats the API reads. "jpg" and "jpeg" are the same format.
12
+ IMAGE_FORMATS = ("png", "jpg", "jpeg")
13
+ #: The ``image_budget`` values the API accepts: the most visual tokens one image may use.
14
+ IMAGE_BUDGETS = (70, 140, 280)
15
+ #: The largest image the API accepts, in bytes (16 MiB).
16
+ MAX_IMAGE_BYTES = 16 * 1024 * 1024
17
+
18
+ _PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
19
+ _JPEG_MAGIC = b"\xff\xd8\xff"
20
+
21
+
22
+ def detect_format(data: bytes) -> Optional[str]:
23
+ """``"png"`` or ``"jpeg"`` from the file's first bytes, or None for anything else."""
24
+ if data.startswith(_PNG_MAGIC):
25
+ return "png"
26
+ if data.startswith(_JPEG_MAGIC):
27
+ return "jpeg"
28
+ return None
29
+
30
+
31
+ def _same_format(a: str, b: str) -> bool:
32
+ jpeg = ("jpg", "jpeg")
33
+ return a == b or (a in jpeg and b in jpeg)
34
+
35
+
36
+ class Image:
37
+ """An image to pass in ``decide(..., assets={reference: Image})``.
38
+
39
+ >>> Image.from_path("receipt.jpg")
40
+ >>> Image.from_bytes(png_bytes) # format detected from the bytes
41
+ >>> Image.from_bytes(data, format="jpeg")
42
+
43
+ The bytes are sent as they are: the client never resizes or re-encodes an image.
44
+ """
45
+
46
+ __slots__ = ("format", "data")
47
+
48
+ def __init__(self, data: bytes, format: Optional[str] = None) -> None:
49
+ if not isinstance(data, (bytes, bytearray, memoryview)):
50
+ raise ValidationError("image data must be bytes")
51
+ data = bytes(data)
52
+ if len(data) > MAX_IMAGE_BYTES:
53
+ raise ValidationError(f"image is {len(data)} bytes; the most the API accepts is {MAX_IMAGE_BYTES} (16 MiB)")
54
+ detected = detect_format(data)
55
+ if format is None:
56
+ if detected is None:
57
+ raise ValidationError("image is not a PNG or JPEG file (the only formats the API reads)")
58
+ format = detected
59
+ else:
60
+ if not isinstance(format, str) or format.lower() not in IMAGE_FORMATS:
61
+ raise ValidationError(f"image format must be one of {', '.join(IMAGE_FORMATS)}, got {format!r}")
62
+ format = format.lower()
63
+ if detected is None or not _same_format(format, detected):
64
+ raise ValidationError(
65
+ f"image bytes are not {format.upper()}"
66
+ + (f" (they look like {detected.upper()})" if detected else " (not a PNG or JPEG file)")
67
+ )
68
+ #: "png", "jpg" or "jpeg".
69
+ self.format: str = format
70
+ #: The file's bytes, unchanged.
71
+ self.data: bytes = data
72
+
73
+ @classmethod
74
+ def from_bytes(cls, data: bytes, format: Optional[str] = None) -> "Image":
75
+ """An image from its file bytes. Without ``format``, it is detected from the bytes (PNG or JPEG)."""
76
+ return cls(data, format)
77
+
78
+ @classmethod
79
+ def from_path(cls, path: Union[str, "os.PathLike[str]"], format: Optional[str] = None) -> "Image":
80
+ """An image read from a file. Without ``format``, it is detected from the bytes (PNG or JPEG), not the file name."""
81
+ size = os.path.getsize(path)
82
+ if size > MAX_IMAGE_BYTES:
83
+ raise ValidationError(f"{os.fspath(path)} is {size} bytes; the most the API accepts is {MAX_IMAGE_BYTES} (16 MiB)")
84
+ with open(path, "rb") as f:
85
+ # read one byte past the limit, so a file that grew, or a device with no size, is still refused
86
+ return cls(f.read(MAX_IMAGE_BYTES + 1), format)
87
+
88
+ def to_dict(self) -> Dict[str, str]:
89
+ """The asset as sent: ``{"type": "image", "format": ..., "data_base64": ...}``."""
90
+ return {"type": "image", "format": self.format, "data_base64": base64.b64encode(self.data).decode("ascii")}
91
+
92
+ def __repr__(self) -> str:
93
+ return f"Image(format={self.format!r}, {len(self.data)} bytes)"
94
+
95
+
96
+ def validate_assets(assets: Any) -> Dict[str, Any]:
97
+ """Check a {reference: image} mapping and build the ``assets`` object. Plain dicts are sent as they are."""
98
+ if not isinstance(assets, Mapping):
99
+ raise ValidationError("assets must be a dict of {reference: Image}")
100
+ out: Dict[str, Any] = {}
101
+ for ref, value in assets.items():
102
+ if not isinstance(ref, str) or not ref:
103
+ raise ValidationError("asset references must be non-empty strings")
104
+ if isinstance(value, Image):
105
+ out[ref] = value.to_dict()
106
+ elif isinstance(value, Mapping):
107
+ out[ref] = dict(value)
108
+ else:
109
+ raise ValidationError(
110
+ f"asset {ref!r} must be an Image (Image.from_path or Image.from_bytes) or a dict "
111
+ '{"type": "image", "format": ..., "data_base64": ...}'
112
+ )
113
+ return out
114
+
115
+
116
+ def validate_image_budget(image_budget: Any) -> int:
117
+ if isinstance(image_budget, bool) or not isinstance(image_budget, int) or image_budget not in IMAGE_BUDGETS:
118
+ raise ValidationError(f"image_budget must be one of {', '.join(map(str, IMAGE_BUDGETS))}, got {image_budget!r}")
119
+ return image_budget
launchables/py.typed ADDED
File without changes
@@ -0,0 +1,103 @@
1
+ """Helpers that build and validate question objects."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict, Iterable, List, Mapping, Optional, Union
6
+
7
+ from .errors import ValidationError
8
+
9
+ MAX_QUESTIONS = 16
10
+ MAX_OPTIONS = 26
11
+ QUESTION_TYPES = ("noul", "choice", "score")
12
+
13
+ Question = Dict[str, Any]
14
+
15
+
16
+ def _instructions(instructions: Any) -> str:
17
+ if not isinstance(instructions, str) or not instructions.strip():
18
+ raise ValidationError("instructions must be a non-empty string")
19
+ return instructions
20
+
21
+
22
+ def noul(instructions: str, true: Optional[str] = None, false: Optional[str] = None) -> Question:
23
+ """A yes/no question. The answer is the probability of yes.
24
+
25
+ ``true`` and ``false`` optionally describe what each answer means.
26
+ """
27
+ q: Question = {"type": "noul", "instructions": _instructions(instructions)}
28
+ if true is not None or false is not None:
29
+ criteria: Dict[str, str] = {}
30
+ if true is not None:
31
+ criteria["true"] = true
32
+ if false is not None:
33
+ criteria["false"] = false
34
+ q["criteria"] = criteria
35
+ return q
36
+
37
+
38
+ def choice(instructions: str, options: Union[Mapping[str, str], Iterable[str]]) -> Question:
39
+ """Pick one label. ``options`` is a list of labels or a {label: description} dict."""
40
+ if isinstance(options, str):
41
+ raise ValidationError("options must be a list of labels or a {label: description} dict")
42
+ if isinstance(options, Mapping):
43
+ criteria: Any = dict(options)
44
+ labels = list(criteria)
45
+ else:
46
+ criteria = list(options)
47
+ labels = criteria
48
+ if not labels:
49
+ raise ValidationError("choice needs at least one option")
50
+ if len(labels) > MAX_OPTIONS:
51
+ raise ValidationError(f"choice supports at most {MAX_OPTIONS} options, got {len(labels)}")
52
+ if not all(isinstance(label, str) and label for label in labels):
53
+ raise ValidationError("choice labels must be non-empty strings")
54
+ if len(set(labels)) != len(labels):
55
+ raise ValidationError("choice labels must be unique")
56
+ return {"type": "choice", "instructions": _instructions(instructions), "criteria": criteria}
57
+
58
+
59
+ def score(instructions: str, levels: Iterable[str]) -> Question:
60
+ """Rate on a scale. ``levels`` describes each level, lowest first (numbered from 0)."""
61
+ if isinstance(levels, (str, Mapping)):
62
+ raise ValidationError("levels must be a list of descriptions, lowest first")
63
+ criteria: List[str] = list(levels)
64
+ if len(criteria) < 2:
65
+ raise ValidationError("score needs at least two levels")
66
+ if not all(isinstance(level, str) and level for level in criteria):
67
+ raise ValidationError("score levels must be non-empty strings")
68
+ return {"type": "score", "instructions": _instructions(instructions), "criteria": criteria}
69
+
70
+
71
+ def validate_questions(questions: Any) -> Dict[str, Question]:
72
+ """Check a {name: question} mapping before it is sent."""
73
+ if not isinstance(questions, Mapping) or not questions:
74
+ raise ValidationError("questions must be a non-empty dict of {name: question}")
75
+ if len(questions) > MAX_QUESTIONS:
76
+ raise ValidationError(f"at most {MAX_QUESTIONS} questions per request, got {len(questions)}")
77
+ out: Dict[str, Question] = {}
78
+ for name, q in questions.items():
79
+ if not isinstance(name, str) or not name:
80
+ raise ValidationError("question names must be non-empty strings")
81
+ if not isinstance(q, Mapping):
82
+ raise ValidationError(f"question {name!r} must be a dict (build it with noul/choice/score)")
83
+ qtype = q.get("type")
84
+ if qtype not in QUESTION_TYPES:
85
+ raise ValidationError(f"question {name!r}: type must be one of {', '.join(QUESTION_TYPES)}, got {qtype!r}")
86
+ _instructions_checked(name, q)
87
+ crit = q.get("criteria")
88
+ if qtype == "choice":
89
+ if not isinstance(crit, (Mapping, list, tuple)) or not crit:
90
+ raise ValidationError(f"question {name!r}: choice needs criteria (options)")
91
+ if len(crit) > MAX_OPTIONS:
92
+ raise ValidationError(f"question {name!r}: at most {MAX_OPTIONS} options, got {len(crit)}")
93
+ elif qtype == "score":
94
+ if not isinstance(crit, (list, tuple)) or not crit:
95
+ raise ValidationError(f"question {name!r}: score needs criteria (a list of level descriptions)")
96
+ out[name] = dict(q)
97
+ return out
98
+
99
+
100
+ def _instructions_checked(name: str, q: Mapping) -> None:
101
+ ins = q.get("instructions")
102
+ if not isinstance(ins, str) or not ins.strip():
103
+ raise ValidationError(f"question {name!r}: instructions must be a non-empty string")
@@ -0,0 +1,135 @@
1
+ """Typed responses."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any, Dict, Optional, Union
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class Usage:
11
+ input_tokens: int = 0
12
+ output_tokens: int = 0
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class NoulAnswer:
17
+ """Yes/no answer. ``noul`` is the probability of yes (0 to 1)."""
18
+
19
+ noul: float
20
+ raw: Dict[str, Any] = field(default_factory=dict, repr=False)
21
+ type: str = "noul"
22
+
23
+ @property
24
+ def probability(self) -> float:
25
+ return self.noul
26
+
27
+ def decide(self, threshold_yes: float = 0.9, threshold_no: float = 0.1) -> str:
28
+ """Return "yes" if p >= threshold_yes, "no" if p <= threshold_no, else "person"
29
+ (hand off to a person)."""
30
+ if not 0.0 <= threshold_no <= threshold_yes <= 1.0:
31
+ raise ValueError("thresholds must satisfy 0 <= threshold_no <= threshold_yes <= 1")
32
+ if self.noul >= threshold_yes:
33
+ return "yes"
34
+ if self.noul <= threshold_no:
35
+ return "no"
36
+ return "person"
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class ChoiceAnswer:
41
+ choice: str
42
+ probabilities: Dict[str, float]
43
+ raw: Dict[str, Any] = field(default_factory=dict, repr=False)
44
+ type: str = "choice"
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class ScoreAnswer:
49
+ score: float
50
+ level: int
51
+ probabilities: Dict[str, float]
52
+ raw: Dict[str, Any] = field(default_factory=dict, repr=False)
53
+ type: str = "score"
54
+
55
+
56
+ Answer = Union[NoulAnswer, ChoiceAnswer, ScoreAnswer]
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class DecisionResponse:
61
+ model: str
62
+ answers: Dict[str, Answer]
63
+ usage: Usage
64
+ raw: Dict[str, Any] = field(default_factory=dict, repr=False)
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class Model:
69
+ id: str
70
+ owned_by: str = ""
71
+ raw: Dict[str, Any] = field(default_factory=dict, repr=False)
72
+
73
+
74
+ @dataclass(frozen=True)
75
+ class KeyInfo:
76
+ """The calling key, from ``client.key()``."""
77
+
78
+ id: str
79
+ name: Optional[str]
80
+ expires_on: Optional[str] # the last day the key works (YYYY-MM-DD), or None if it never expires
81
+ days_left: Optional[int]
82
+ workspace: Optional[str]
83
+ rate_limit_per_minute: Optional[int]
84
+ daily_limit: Optional[int]
85
+ paused: bool
86
+ pause_reason: Optional[str] = None # "credit", "budget" or "model" when paused
87
+ raw: Dict[str, Any] = field(default_factory=dict, repr=False)
88
+
89
+
90
+ @dataclass(frozen=True)
91
+ class KeyExpiry:
92
+ """What the client last learnt about its key's expiry, from the response headers."""
93
+
94
+ key_id: Optional[str]
95
+ expires_on: str # the last day the key works (YYYY-MM-DD)
96
+ days_left: int # whole days from today (UTC); 0 on the last day
97
+
98
+
99
+ def parse_key_info(data: Dict[str, Any]) -> KeyInfo:
100
+ return KeyInfo(
101
+ id=str(data.get("id", "")), name=data.get("name"), expires_on=data.get("expires_on"),
102
+ days_left=data.get("days_left"), workspace=data.get("workspace"),
103
+ rate_limit_per_minute=data.get("rate_limit_per_minute"), daily_limit=data.get("daily_limit"),
104
+ paused=bool(data.get("paused", False)), pause_reason=data.get("pause_reason"), raw=data,
105
+ )
106
+
107
+
108
+ def parse_answer(data: Dict[str, Any]) -> Answer:
109
+ kind = data.get("type")
110
+ if kind == "noul":
111
+ return NoulAnswer(noul=float(data["noul"]), raw=data)
112
+ if kind == "choice":
113
+ return ChoiceAnswer(
114
+ choice=data["choice"],
115
+ probabilities={k: float(v) for k, v in data.get("probabilities", {}).items()},
116
+ raw=data,
117
+ )
118
+ if kind == "score":
119
+ return ScoreAnswer(
120
+ score=float(data["score"]),
121
+ level=int(data["level"]),
122
+ probabilities={k: float(v) for k, v in data.get("probabilities", {}).items()},
123
+ raw=data,
124
+ )
125
+ raise ValueError(f"unknown answer type: {kind!r}")
126
+
127
+
128
+ def parse_response(data: Dict[str, Any]) -> DecisionResponse:
129
+ usage = data.get("usage") or {}
130
+ return DecisionResponse(
131
+ model=data.get("model", ""),
132
+ answers={name: parse_answer(a) for name, a in (data.get("answers") or {}).items()},
133
+ usage=Usage(int(usage.get("input_tokens", 0)), int(usage.get("output_tokens", 0))),
134
+ raw=data,
135
+ )
@@ -0,0 +1,199 @@
1
+ Metadata-Version: 2.4
2
+ Name: launchables
3
+ Version: 0.4.0
4
+ Summary: Python client for the Launchables Decision API
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://www.launchables.ai/docs
7
+ Project-URL: Documentation, https://www.launchables.ai/docs
8
+ Project-URL: Repository, https://github.com/launchables-ai/launchables-sdk
9
+ Project-URL: Issues, https://github.com/launchables-ai/launchables-sdk/issues
10
+ Keywords: launchables,decision,api,llm
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Typing :: Typed
13
+ Requires-Python: >=3.9
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Dynamic: license-file
17
+
18
+ # launchables (Python)
19
+
20
+ Python client for the Launchables Decision API. Standard library only, Python 3.9+.
21
+
22
+ ```
23
+ pip install launchables
24
+ ```
25
+
26
+ ## Quick start
27
+
28
+ ```python
29
+ from launchables import Launchables, noul
30
+
31
+ client = Launchables() # reads LAUNCHABLES_API_TOKEN
32
+
33
+ resp = client.decide(
34
+ "Customer bought the item 12 days ago and has no receipt. "
35
+ "Policy: refunds within 30 days with proof of purchase.",
36
+ {"refund": noul("Is a refund permitted under the policy?")},
37
+ )
38
+
39
+ answer = resp.answers["refund"]
40
+ print(answer.probability) # probability of yes, e.g. 0.04
41
+ print(answer.decide(threshold_yes=0.9, threshold_no=0.1)) # "yes" | "no" | "person"
42
+ print(resp.usage.input_tokens, resp.model)
43
+ ```
44
+
45
+ `decide` returns a `DecisionResponse` with `.answers`, `.usage`, `.model` and `.raw` (the untouched JSON). `state` may be a string or a dict. To include images, see [Images](#images).
46
+
47
+ ### Question types
48
+
49
+ ```python
50
+ from launchables import noul, choice, score
51
+
52
+ questions = {
53
+ "refund": noul("Is a refund permitted?", true="Policy clearly allows it", false="Policy clearly forbids it"),
54
+ "topic": choice("What is this about?", ["billing", "returns", "other"]), # or {label: description}
55
+ "urgency": score("How urgent is it?", ["not urgent", "low", "medium", "high"]), # lowest level first, numbered from 0
56
+ }
57
+ resp = client.decide(state, questions)
58
+
59
+ resp.answers["topic"].choice # "returns"
60
+ resp.answers["topic"].probabilities # {"billing": 0.06, "returns": 0.89, ...}
61
+ resp.answers["urgency"].level # 2
62
+ resp.answers["urgency"].score # 1.92
63
+ resp.answers["urgency"].probabilities # {"0": 0.03, "1": 0.12, ...}
64
+ ```
65
+
66
+ Helpers validate locally and raise `ValidationError` before any request is sent: at most 16 questions per request, at most 26 options per choice, non-empty instructions.
67
+
68
+ ### Other calls
69
+
70
+ ```python
71
+ client.models() # [Model(id="myles-g-12b", ...)]
72
+ client.health() # {"status": "ok"}
73
+ ```
74
+
75
+ `models()` and `health()` need no token.
76
+
77
+ ## Images
78
+
79
+ Pass images in `assets`, keyed by a reference of your choosing, and write that reference wherever the model should see the image: in the state (a text state, or any string value in a JSON state), a question's instructions, or a criterion's description. Option labels are not searched.
80
+
81
+ ```python
82
+ from launchables import Image, Launchables, noul
83
+
84
+ client = Launchables()
85
+
86
+ resp = client.decide(
87
+ {"receipt": "receipt_photo", "note": "Customer asks for a refund"},
88
+ {"total_matches": noul("Does the total printed on receipt_photo equal 23.40?")},
89
+ assets={"receipt_photo": Image.from_path("receipt.jpg")},
90
+ image_budget=140, # optional: 70, 140 or 280 (the default)
91
+ )
92
+ ```
93
+
94
+ `Image.from_path(path)` and `Image.from_bytes(data)` detect PNG or JPEG from the file's first bytes; pass `format="png"`, `"jpg"` or `"jpeg"` to state it (it must match the bytes). A plain dict in the wire shape, `{"type": "image", "format": "jpeg", "data_base64": "..."}`, is accepted as it is. References are matched as plain, case-sensitive text; every place a reference appears shows the image there, and when one reference contains another the longer one wins.
95
+
96
+ `image_budget` is the most visual tokens one image may use. Lower is cheaper and faster but sees less detail (small print suffers first). Any value other than 70, 140 or 280 raises `ValidationError` before sending; leave it out to get the server default of 280.
97
+
98
+ Limits, checked by the server (each breach is an `InvalidRequestError` whose message names the asset):
99
+
100
+ - PNG or JPEG only, still images, and the bytes must match the format. The helper detects the format from the bytes and refuses anything else before sending.
101
+ - At most 16 MiB per image (the helper checks this too). Width and height each from 280 to 1568 pixels. Images are never resized or re-encoded, by the client or the server, so resize larger images yourself first.
102
+ - At most 8 assets per request, and at most 8 images shown in any one question (each use of a reference counts).
103
+ - Every asset must be referenced at least once. A reference inside a text state must fall within its first 20,000 characters.
104
+
105
+ Images count as input tokens and are included in `usage.input_tokens`. At budget 280 one image costs up to about 280 tokens, at 140 up to about 140, at 70 up to about 70. An image referenced in the state is billed once per request however many questions read it; one referenced in a question's instructions or criteria is billed for that question, once per use.
106
+
107
+ ## Key expiry
108
+
109
+ Every API key expires. The client reads the expiry date from each response, so your program can plan rotation instead of finding out when the key stops working.
110
+
111
+ ```python
112
+ def on_expiry(expiry):
113
+ # called once per key and expiry date when 14 days or fewer are left: alert your team, or start a rotation job
114
+ alert_team(f"Launchables key {expiry.key_id} expires on {expiry.expires_on} ({expiry.days_left} days left)")
115
+
116
+ client = Launchables(on_key_expiry=on_expiry)
117
+
118
+ client.key()
119
+ # KeyInfo(id="c_1a2b3c4d", name="prod", expires_on="2027-01-13", days_left=89, workspace=None,
120
+ # rate_limit_per_minute=600, daily_limit=10000000, paused=False, pause_reason=None)
121
+
122
+ client.key_expiry # KeyExpiry(key_id, expires_on, days_left) from the last response, or None
123
+ ```
124
+
125
+ Without `on_key_expiry`, the client issues one `KeyExpiryWarning` when 14 days or fewer are left. `key()` counts as no request and no tokens, and works for a paused key so you can see why it is paused (`pause_reason`). The expiry headers add nothing to your token count. To replace a key without downtime, roll it on the API keys page of the console: the old key keeps working until the end of the next day.
126
+
127
+ ## Managing keys
128
+
129
+ To rotate keys from your own scripts, use an admin key. An owner makes one on the API keys page of the console (two-step sign-in must be on). Admin keys start with `launchables_admin_`, always expire, and can only manage your organisation's API keys: they cannot call the Decision API.
130
+
131
+ ```python
132
+ client = Launchables(admin_key=os.environ["LAUNCHABLES_ADMIN_KEY"]) # or just set LAUNCHABLES_ADMIN_KEY
133
+
134
+ page = client.admin.keys.list() # {"data": [{"id", "name", "prefix", "workspace", "expires_on", "last_used_on", "status", ...}], "has_more", "next_before"}
135
+ for key in client.admin.keys.list_all():
136
+ print(key["id"], key["status"])
137
+
138
+ made = client.admin.keys.create("staging", expires_in_days=90) # workspace_id is optional
139
+ made["key"] # the full key, shown only this once
140
+
141
+ rolled = client.admin.keys.roll("c_1a2b3c4d")
142
+ rolled["key"] # the new key; rolled["replaces"]["expires_on"] is when the old one stops (the end of tomorrow)
143
+
144
+ client.admin.keys.revoke("c_1a2b3c4d")
145
+ ```
146
+
147
+ Key lifetimes are 30, 90, 180 or 365 days (90 by default), never longer than your organisation allows. These calls go to `https://console.launchables.ai` (`admin_base_url` to change it) and may be made 120 times a minute per admin key. A missing key or workspace raises `NotFoundError` (404); the key limit or an archived workspace raises `ConflictError` (409); both are kinds of `InvalidRequestError`. `create` and `roll` are retried only after a 429, so a retry never makes a second key. Every change shows in Activity in the console.
148
+
149
+ ## Error handling
150
+
151
+ All errors derive from `LaunchablesError` and carry `.status`, `.message` (the server's message), `.body` and `.type` (the server's error type, such as `"out_of_credit"`, or `None` if it sent none).
152
+
153
+ | Error | When |
154
+ | --- | --- |
155
+ | `AuthenticationError` | 401, or no key (or admin key) given or found |
156
+ | `OutOfCreditError` | 402: the account has run out of prepaid credit (`.type` `"out_of_credit"`, top up in the console), or the key's workspace has reached its monthly budget (`.type` `"budget_exceeded"`) |
157
+ | `PermissionDeniedError` | 403: the key's workspace may not use this model (`.type` `"model_not_allowed"`), or the admin key's maker is no longer an owner |
158
+ | `RateLimitError` | 429 (`.retry_after` seconds, if sent) |
159
+ | `InvalidRequestError` | 400, 411, 413, 422 and other 4xx; `ValidationError` is the local pre-flight subclass. `.type` says what was wrong with an image: `"invalid_assets"`, `"unsupported_image_format"`, `"invalid_image"`, `"image_too_large"`, `"image_dimensions"`, `"too_many_images"`, `"unreferenced_asset"` or `"image_reference_truncated"` (400), or `"invalid_image_budget"` (422). |
160
+ | `NotFoundError`, `ConflictError` | 404 and 409 from the key management API (subclasses of `InvalidRequestError`) |
161
+ | `APIError` | 5xx |
162
+ | `APIConnectionError` | could not reach the server (including timeouts) |
163
+
164
+ ```python
165
+ from launchables import OutOfCreditError, RateLimitError, InvalidRequestError, LaunchablesError
166
+
167
+ try:
168
+ resp = client.decide(state, questions)
169
+ except OutOfCreditError as e:
170
+ print("workspace budget reached" if e.type == "budget_exceeded" else "top up credit")
171
+ except RateLimitError as e:
172
+ print("slow down", e.retry_after)
173
+ except InvalidRequestError as e:
174
+ print(e.status, e.message)
175
+ except LaunchablesError as e:
176
+ print("failed:", e)
177
+ ```
178
+
179
+ ## Retries
180
+
181
+ 429, 502, 503 and connection errors are retried up to `max_retries` times (default 3) with exponential backoff of 0.5s, 1s, 2s. A `Retry-After` header (seconds) is honoured instead, capped at 60s. Other errors, including 402 and 403, are raised immediately. `timeout` (seconds, default 30) applies to each attempt.
182
+
183
+ ```python
184
+ client = Launchables(api_key="launchables_...", timeout=10, max_retries=5)
185
+ ```
186
+
187
+ ## Self-hosted endpoints
188
+
189
+ ```python
190
+ client = Launchables(base_url="https://decisions.internal.example.com")
191
+ ```
192
+
193
+ Requests carry `User-Agent: launchables-python/<version>`.
194
+
195
+ ## Tests
196
+
197
+ ```
198
+ PYTHONPATH=src python -m unittest discover -s tests -t .
199
+ ```
@@ -0,0 +1,14 @@
1
+ launchables/__init__.py,sha256=JJqmQjbpOjItgPSFrGQTA_b1cf6uGpk7X14qXNo3T4w,1350
2
+ launchables/_version.py,sha256=42STGor_9nKYXumfeV5tiyD_M8VdcddX7CEexmibPBk,22
3
+ launchables/admin.py,sha256=w4To2ApU1Hh41yNtQ3plrA5oM74wa2akuorQ43jdupw,3569
4
+ launchables/client.py,sha256=gmRoHiHLvLl9Uid76A3FwzfIILq4t0VKpN438G4RBzo,11913
5
+ launchables/errors.py,sha256=l37-xoOdR2r87FKCTciPf4TtZJnIfZY8_KHCQOhXbx4,3633
6
+ launchables/images.py,sha256=Vcz6RDY_QnGpG_z4XX_iY2VbNido6L-LImuOyDk_peY,5166
7
+ launchables/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ launchables/questions.py,sha256=P8q9g3T2g0sjs1yn38CniZMmf2LJt3xYXKwzThmJ2m8,4673
9
+ launchables/responses.py,sha256=WGe5Pd5AV-7wRaulQ2t61VTiwcQThHWTu0qAoqwWJKw,4141
10
+ launchables-0.4.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
11
+ launchables-0.4.0.dist-info/METADATA,sha256=uAFGKUZD5oM3uwu3sIY9Tf7omB9djwFwdIcu6QTpsdI,10358
12
+ launchables-0.4.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
13
+ launchables-0.4.0.dist-info/top_level.txt,sha256=CV8K16PI20sp5sAuC3QrNq5DiShyAS5nZv8zfTfGuXk,12
14
+ launchables-0.4.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ launchables